-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
567 lines (525 loc) · 18.9 KB
/
server.ts
File metadata and controls
567 lines (525 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import type { JobId } from "@arcp/core";
import type { BearerIdentity } from "@arcp/core/auth";
import { buildEnvelope } from "@arcp/core/envelope";
import {
ARCPError,
InvalidRequestError,
ResumeWindowExpiredError,
UnauthenticatedError,
} from "@arcp/core/errors";
import {
type Logger,
sessionLogger as makeSessionLogger,
rootLogger,
} from "@arcp/core/logger";
import type {
AgentInventoryEntry,
Capabilities,
Envelope,
SessionHelloPayload,
SessionWelcomePayload,
} from "@arcp/core/messages";
import { negotiateCapabilities } from "@arcp/core/state";
import { EventLog } from "@arcp/core/store";
import type { Transport } from "@arcp/core/transport";
import { newMessageId, newSessionId } from "@arcp/core/util";
import { intersectFeatures, V1_1_FEATURES } from "@arcp/core/version";
import { AgentRegistry } from "./agent-registry.js";
import { JobRunner } from "./job-runner.js";
import type { Job } from "./job.js";
import { handleResume } from "./server-resume.js";
import { handleJobSubscribe, handleListJobs } from "./server-subscribe.js";
import {
type SessionContext,
SessionContext as SessionContextCtor,
} from "./session-context.js";
import { IdempotencyStore, newResumeToken, ResumeStore } from "./stores.js";
import type { AgentHandler, ARCPServerOptions } from "./types.js";
export { SessionContext } from "./session-context.js";
// ARCP v1.1 (additive over v1.0) runtime.
//
// v1.0 dispatch: session.hello → session.welcome | session.error.
// Post-welcome: job.submit, job.cancel, session.bye. Outbound: job.accepted,
// job.event, job.result, job.error, session.welcome, session.bye, session.error.
//
// v1.1 adds: session.ping, session.pong, session.ack, session.list_jobs,
// session.jobs, job.subscribe, job.subscribed, job.unsubscribe. Plus the
// `progress`/`result_chunk` event kinds, `lease_constraints` (expires_at),
// `cost.budget`, and agent versioning.
const DEFAULT_HEARTBEAT_SECONDS = 30;
const DEFAULT_RESUME_WINDOW_SECONDS = 600;
const DEFAULT_GRACE_MS = 30_000;
/**
* Top-level ARCP runtime/server (§6–§14).
*
* Hosts a set of named agents (optionally versioned) and accepts sessions
* over any {@link Transport}. Each accepted session drives the §6
* handshake, dispatches `job.submit`/`job.cancel`/`session.bye` and (v1.1)
* `session.ping`/`session.pong`/`session.ack`/`session.list_jobs`/
* `job.subscribe`/`job.unsubscribe`, and emits `job.event`/`job.result`/
* `job.error` envelopes back to the client.
*
* One server instance can serve many concurrent sessions. The runtime
* maintains:
*
* - an event log (for §6.3 resume replay and §7.6 history replay),
* - an in-process idempotency store (`(principal, idempotency_key) → job_id`),
* - a resume-token store with periodic sweep (§14 window expiry),
* - per-session DoS caps (§14),
* - a global jobs registry (for §6.6 list and §7.6 subscribe).
*/
export class ARCPServer {
public readonly eventLog: EventLog;
public readonly logger: Logger;
private readonly agentRegistry = new AgentRegistry();
/** Internal: read by `JobRunner` for idempotency lookups on `job.submit`. */
public readonly idempotencyStore = new IdempotencyStore();
public readonly resumeStore = new ResumeStore();
private readonly jobRunner = new JobRunner(this);
/** Live sessions, indexed by session_id (only those past welcome). */
public readonly sessions = new Map<string, SessionContext>();
/**
* Global jobs registry for cross-session features (§6.6 listing,
* §7.6 subscription). Indexed by job_id.
*/
public readonly globalJobs = new Map<string, Job>();
/** job_id → set of subscriber SessionContexts. */
public readonly subscribers = new Map<string, Set<SessionContext>>();
private resumeSweep: ReturnType<typeof setInterval> | null = null;
public constructor(public readonly options: ARCPServerOptions) {
this.eventLog = options.eventLog ?? new EventLog();
this.logger = options.logger ?? rootLogger;
this.resumeSweep = setInterval(() => {
this.sweepResume();
}, 60_000);
this.resumeSweep.unref();
}
/** v1.1 feature flags this runtime advertises. Defaults to every v1.1 feature. */
public get advertisedFeatures(): readonly string[] {
return this.options.features ?? V1_1_FEATURES;
}
/**
* Register an unversioned agent handler. Submissions with a bare `agent`
* name match this. If a versioned handler is also registered, bare-name
* submissions resolve to the default version (or the unversioned handler
* if no default is set).
*/
public registerAgent<Input = unknown, Result = unknown>(
name: string,
handler: AgentHandler<Input, Result>,
): void {
this.agentRegistry.register(name, handler);
}
/**
* v1.1 §7.5 — register a versioned agent handler. The same `name` MAY have
* multiple versions; use {@link setDefaultAgentVersion} to choose which one
* resolves for bare-name submissions.
*/
public registerAgentVersion<Input = unknown, Result = unknown>(
name: string,
version: string,
handler: AgentHandler<Input, Result>,
): void {
this.agentRegistry.registerVersion(name, version, handler);
}
/** v1.1 §7.5 — set the default version for bare-name submissions. */
public setDefaultAgentVersion(name: string, version: string): void {
this.agentRegistry.setDefaultVersion(name, version);
}
public hasAgent(name: string): boolean {
return this.agentRegistry.has(name);
}
/**
* Resolve a parsed agent reference to a concrete handler. Returns the
* resolved version (may be empty string for unversioned). Throws
* `AgentNotAvailableError` / `AgentVersionNotAvailableError` per §7.5.
*/
public resolveAgent(
name: string,
version: string | null,
): { handler: AgentHandler; version: string } {
return this.agentRegistry.resolve(name, version);
}
/** Build the rich agent inventory shape (§6.2 / §7.5) for advertisement. */
public getAgentInventory(): AgentInventoryEntry[] {
return this.agentRegistry.inventory();
}
/**
* Adopt a {@link Transport} as a new session. Returns the
* {@link SessionContext}; the handshake completes asynchronously.
*/
public accept(transport: Transport): SessionContext {
const ctx = new SessionContextCtor(transport, this, this.logger);
transport.onFrame((frame) => ctx.dispatchRaw(frame));
transport.onClose(() => {
const terminal: ReadonlySet<string> = new Set(["rejected", "closing"]);
if (terminal.has(ctx.state.phase)) return;
if (ctx.state.isAccepted) {
ctx.state.transition("closing");
} else {
ctx.state.transition("rejected");
}
});
this.registerHandshakeHandlers(ctx);
return ctx;
}
/** Close the runtime and the underlying event log. */
public async close(): Promise<void> {
if (this.resumeSweep !== null) {
clearInterval(this.resumeSweep);
this.resumeSweep = null;
}
await this.eventLog.close();
}
/** Internal: drop a session from the live map. */
public dropSession(ctx: SessionContext): void {
const id = ctx.state.id;
if (id !== undefined) this.sessions.delete(id);
}
// ---------------------------------------------------------------------
// Handshake
// ---------------------------------------------------------------------
private registerHandshakeHandlers(ctx: SessionContext): void {
ctx.registerHandler("session.hello", async (env) => {
await this.handleSessionHello(ctx, env);
});
}
private async handleSessionHello(
ctx: SessionContext,
env: Envelope,
): Promise<void> {
if (env.type !== "session.hello") return;
if (ctx.state.phase !== "opening") {
await ctx.emitSessionError(
new InvalidRequestError("session.hello received in non-opening phase"),
);
return;
}
const identity = await this.authenticateHello(ctx, env.payload);
if (identity === null) return;
if (env.payload.resume !== undefined) {
await handleResume({
server: this,
ctx,
identity,
payload: env.payload,
});
return;
}
await this.acceptFreshSession(ctx, identity, env.payload);
}
private async authenticateHello(
ctx: SessionContext,
payload: SessionHelloPayload,
): Promise<BearerIdentity | null> {
try {
return await this.authenticate(payload.auth);
} catch (error) {
const wrapped =
error instanceof ARCPError
? error
: new UnauthenticatedError("Auth failed");
ctx.logger.info(
{ scheme: payload.auth.scheme },
"rejecting session.hello (auth)",
);
await ctx.emitSessionError(wrapped);
return null;
}
}
private async acceptFreshSession(
ctx: SessionContext,
identity: BearerIdentity,
payload: SessionHelloPayload,
): Promise<void> {
const sessionId = newSessionId();
ctx.state.assignId(sessionId);
ctx.state.assignIdentity(identity);
const negotiated = this.makeNegotiatedCapabilities(payload, ctx);
ctx.state.assignCapabilities(negotiated);
this.bindLogger(ctx, payload.client.name);
const resumeWindowSec =
this.options.resumeWindowSeconds ?? DEFAULT_RESUME_WINDOW_SECONDS;
const resumeToken = newResumeToken();
this.resumeStore.set(sessionId, {
sessionId,
resumeToken,
expiresAt: Date.now() + resumeWindowSec * 1000,
});
const welcome = this.buildWelcomePayload(ctx, negotiated, {
resumeToken,
resumeWindowSec,
});
ctx.state.transition("accepted");
this.sessions.set(sessionId, ctx);
await ctx.send(
buildEnvelope({
id: newMessageId(),
type: "session.welcome" as const,
payload: welcome,
optional: { session_id: sessionId },
}),
);
ctx.logger.info(
{ session_id: sessionId, principal: identity.principal },
"session welcomed",
);
this.registerPostHandshakeHandlers(ctx);
ctx.startHeartbeat();
}
public buildWelcomePayload(
ctx: SessionContext,
negotiated: Capabilities,
args: {
resumeToken: ReturnType<typeof newResumeToken>;
resumeWindowSec: number;
},
): SessionWelcomePayload {
const heartbeatSec =
this.options.heartbeatIntervalSeconds ?? DEFAULT_HEARTBEAT_SECONDS;
return {
runtime: this.options.runtime,
resume_token: args.resumeToken,
resume_window_sec: args.resumeWindowSec,
...(ctx.hasFeature("heartbeat")
? { heartbeat_interval_sec: heartbeatSec }
: {}),
capabilities: negotiated,
};
}
/**
* Build the welcome capabilities: intersect features with the client's
* advertised list and store the result on the session context.
*/
public makeNegotiatedCapabilities(
payload: SessionHelloPayload,
ctx: SessionContext,
): Capabilities {
const base: Capabilities = { ...this.options.capabilities };
// Advertise the rich agent inventory shape when the agent_versions
// feature is negotiated and we have versioned handlers; else fall back to
// the v1.0 flat shape (or what the caller supplied).
const clientFeatures = payload.capabilities?.features;
const features = intersectFeatures(this.advertisedFeatures, clientFeatures);
ctx.assignNegotiatedFeatures(features);
if (features.includes("agent_versions") || base.agents === undefined) {
const inventory = this.getAgentInventory();
if (inventory.length > 0) {
base.agents = inventory;
}
}
if (features.length > 0) {
base.features = features;
}
return negotiateCapabilities(payload.capabilities, base);
}
public bindLogger(ctx: SessionContext, clientName: string): void {
const sessionId = ctx.state.id;
if (sessionId === undefined) return;
ctx.logger = makeSessionLogger(this.logger, sessionId).child({
client: clientName,
});
}
public registerPostHandshakeHandlers(ctx: SessionContext): void {
this.registerJobLifecycleHandlers(ctx);
this.registerSessionControlHandlers(ctx);
this.registerListJobsHandler(ctx);
this.registerSubscriptionHandlers(ctx);
}
private registerJobLifecycleHandlers(ctx: SessionContext): void {
ctx.registerHandler("job.submit", async (env) => {
if (env.type !== "job.submit") return;
await this.jobRunner.handleJobSubmit(ctx, env);
});
ctx.registerHandler("job.cancel", async (env) => {
if (env.type !== "job.cancel") return;
await this.handleJobCancel(ctx, env);
});
ctx.registerHandler("session.bye", async (env) => {
if (env.type !== "session.bye") return;
ctx.jobs.cancelAll("session closed");
try {
ctx.state.transition("closing");
} catch {
// already in terminal phase
}
await ctx.terminate(env.payload.reason);
});
}
private registerSessionControlHandlers(ctx: SessionContext): void {
// v1.1 §6.4 — heartbeat (handled even if not negotiated; receivers always
// respond to ping per §6.4 to support staggered rollouts).
ctx.registerHandler("session.ping", async (env) => {
if (env.type !== "session.ping") return;
const sessionId = ctx.state.id;
if (sessionId === undefined) return;
// Direct transport.send — heartbeats are NOT counted in event_seq.
await ctx.transport.send(
buildEnvelope({
id: newMessageId(),
type: "session.pong" as const,
payload: {
ping_nonce: env.payload.nonce,
received_at: new Date().toISOString(),
},
optional: { session_id: sessionId },
}),
);
});
ctx.registerHandler("session.pong", (env) => {
if (env.type !== "session.pong") return;
ctx.handlePong(env.payload.ping_nonce);
});
// v1.1 §6.5 — event acknowledgement.
ctx.registerHandler("session.ack", (env) => {
if (env.type !== "session.ack") return;
if (!ctx.hasFeature("ack")) return;
ctx.recordAck(env.payload.last_processed_seq);
});
}
private registerListJobsHandler(ctx: SessionContext): void {
// v1.1 §6.6 — job listing.
ctx.registerHandler("session.list_jobs", async (env) => {
if (env.type !== "session.list_jobs") return;
if (!ctx.hasFeature("list_jobs")) {
await ctx.emitSessionError(
new InvalidRequestError(
"session.list_jobs requires the 'list_jobs' feature",
),
);
return;
}
await handleListJobs(this, ctx, env);
});
}
private registerSubscriptionHandlers(ctx: SessionContext): void {
// v1.1 §7.6 — subscription.
ctx.registerHandler("job.subscribe", async (env) => {
if (env.type !== "job.subscribe") return;
if (!ctx.hasFeature("subscribe")) {
await ctx.emitSessionError(
new InvalidRequestError(
"job.subscribe requires the 'subscribe' feature",
),
);
return;
}
await handleJobSubscribe(this, ctx, env);
});
ctx.registerHandler("job.unsubscribe", (env) => {
if (env.type !== "job.unsubscribe") return;
if (!ctx.hasFeature("subscribe")) return;
const jobId = env.payload.job_id;
const stop = ctx.subscriptions.get(jobId);
if (stop !== undefined) {
stop();
ctx.subscriptions.delete(jobId);
}
});
}
// §7 Jobs: handleJobSubmit and the run-loop live in ./job-runner.ts.
private async handleJobCancel(
ctx: SessionContext,
env: Envelope,
): Promise<void> {
if (env.type !== "job.cancel") return;
const jobId = env.job_id;
if (jobId === undefined) {
await ctx.emitSessionError(
new InvalidRequestError("job.cancel requires job_id"),
);
return;
}
const job = ctx.jobs.get(jobId);
if (job === undefined) {
await this.emitCancelTargetMissing(ctx, jobId);
return;
}
if (job.isTerminal) return;
job.cancel(env.payload.reason ?? "client_cancel");
this.scheduleCancelGrace(job);
}
private async emitCancelTargetMissing(
ctx: SessionContext,
jobId: JobId,
): Promise<void> {
// v1.1 §7.6 — subscription does NOT grant cancel authority. If the job
// exists but this session is only a subscriber, refuse with
// PERMISSION_DENIED rather than masquerading as JOB_NOT_FOUND.
if (this.globalJobs.get(jobId) !== undefined) {
await ctx.emitJobError(jobId, {
final_status: "error",
code: "PERMISSION_DENIED",
message: "Subscription does not confer cancel authority",
retryable: false,
});
return;
}
await ctx.emitJobError(jobId, {
final_status: "error",
code: "JOB_NOT_FOUND",
message: `Job "${jobId}" not found in this session`,
retryable: false,
});
}
private scheduleCancelGrace(job: Job): void {
// §7.4: default 30s; force-emit cancelled error on expiry.
const graceMs = this.options.cancelGraceMs ?? DEFAULT_GRACE_MS;
const timer = setTimeout(() => {
if (job.isTerminal) return;
void job.emitErrorEnvelope({
final_status: "cancelled",
code: "CANCELLED",
message: `Cancellation grace expired (${graceMs}ms)`,
retryable: false,
});
}, graceMs);
timer.unref();
}
// ---------------------------------------------------------------------
// Auth
// ---------------------------------------------------------------------
private async authenticate(
auth: SessionHelloPayload["auth"],
): Promise<BearerIdentity> {
// Bearer is the only scheme today; future schemes will widen this union.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (auth.scheme === "bearer") {
const verifier = this.options.bearer;
if (verifier === undefined) {
throw new InvalidRequestError(
"Runtime has no bearer verifier configured",
);
}
if (auth.token === undefined) {
throw new UnauthenticatedError("bearer scheme requires `token`");
}
return verifier.verify(auth.token);
}
throw new InvalidRequestError(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Auth scheme "${auth.scheme}" not supported`,
);
}
// ---------------------------------------------------------------------
// Internal sweeps
// ---------------------------------------------------------------------
private sweepResume(): void {
const now = Date.now();
this.resumeStore.sweep(now);
// Also expire idle sessions past the window.
const windowMs =
(this.options.resumeWindowSeconds ?? DEFAULT_RESUME_WINDOW_SECONDS) *
1000;
for (const ctx of this.sessions.values()) {
if (now - ctx.lastActivityAt > windowMs) {
void ctx.emitSessionError(
new ResumeWindowExpiredError("session idle past resume_window_sec"),
);
}
}
}
// §10 delegation child-job creation lives on `JobRunner` in ./job-runner.ts.
}
// Job's `submitterPrincipal` and `owningSession` fields are declared in
// `./job.ts` (Job class definition) for §6.6/§7.6 cross-session features.