@hosty-sdk/app 0.55.0 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,7 +49,10 @@ export declare class AgentClient {
49
49
  configureSession(sessionId: string, configurationId: string, input: AgentConfigurationCreate, options?: AgentRequestOptions): Promise<AgentSession>;
50
50
  startRun(sessionId: string, runId: string, input: AgentRunInput, options?: AgentRequestOptions): Promise<AgentRunSnapshot>;
51
51
  run(runId: string, options?: AgentRequestOptions): Promise<AgentRunSnapshot>;
52
+ closure(runId: string, options?: AgentRequestOptions): Promise<import("./agent.js").AgentRunClosure>;
53
+ discardDelivery(runId: string, requestId: string, options?: AgentRequestOptions): Promise<import("./agent.js").AgentDiscardReceipt>;
52
54
  respond(runId: string, input: AgentResponseInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
55
+ stop(runId: string, requestId?: string, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
53
56
  cancel(runId: string, input: AgentCancelInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
54
57
  control(runId: string, requestId: string, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
55
58
  runControl(runId: string, input: AgentRunControlInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
@@ -97,6 +100,11 @@ export declare function watchAgentHistory(options: AgentHistoryOptions): AsyncGe
97
100
  export declare function watchLiveAgentHistory(options: AgentHistoryOptions & {
98
101
  onReady: (boundary: string) => void | Promise<void>;
99
102
  }): AsyncGenerator<AgentHistoryObservation>;
103
+ export declare function acknowledgeAgentHistory(options: AgentHistoryOptions, receipt: {
104
+ sessionId: string;
105
+ epoch: string;
106
+ through: number;
107
+ }): Promise<void>;
100
108
  export declare function readAgentHistoryStates(options: AgentHistoryOptions & HistoryPageOptions & {
101
109
  afterSession?: string;
102
110
  }): Promise<{
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { AgentApiError, } from "./agent.js";
3
- import { agentReplayCursor, validateAgentEvent, validateAgentRunSnapshot, validateAgentRequest, validateAgentSession, validateAgentCapabilities, validateAgentControlReceipt } from "./agent-server.js";
3
+ import { agentReplayCursor, validateAgentEvent, validateAgentRunClosure, validateAgentRunSnapshot, validateAgentRequest, validateAgentSession, validateAgentCapabilities, validateAgentControlReceipt } from "./agent-server.js";
4
4
  const MAX_BYTES = 1024 * 1024;
5
5
  const sha = (body) => createHash("sha256").update(body, "utf8").digest("hex");
6
6
  const segment = (id) => {
@@ -22,7 +22,7 @@ export const prepareAgentSessionCreate = (sessionId, input) => prepareAgentReque
22
22
  export const prepareAgentConfiguration = (sessionId, configurationId, input) => prepareAgentRequest("sessions.configure", "PUT", `/sessions/${segment(sessionId)}/configurations/${segment(configurationId)}`, input, { sessionId });
23
23
  export const prepareAgentRun = (sessionId, runId, input) => prepareAgentRequest("runs.start", "PUT", `/sessions/${segment(sessionId)}/runs/${segment(runId)}`, input, { sessionId, runId, resources: input.resources, ceiling: { mcp: input.mcp, resources: input.resources, configurationRevision: input.configurationRevision } });
24
24
  export const prepareAgentResponse = (runId, input) => prepareAgentRequest("runs.respond", "POST", `/runs/${segment(runId)}/responses`, input, { runId });
25
- export const prepareAgentCancel = (runId, input) => prepareAgentRequest("runs.cancel", "POST", `/runs/${segment(runId)}/cancel`, input, { runId, ...(input.fenceIfNotAdmitted ? { sessionId: input.fenceIfNotAdmitted.sessionId } : {}) });
25
+ export const prepareAgentCancel = (runId, input) => prepareAgentRequest("runs.cancel", "PUT", `/runs/${segment(runId)}/stop`, input, { runId, ...(input.fenceIfNotAdmitted ? { sessionId: input.fenceIfNotAdmitted.sessionId } : {}) });
26
26
  export const prepareAgentControl = (runId, input) => prepareAgentRequest("runs.control", "POST", `/runs/${segment(runId)}/controls`, input, { runId });
27
27
  export const prepareAgentAttachmentChunk = (attachmentId, index, input) => prepareAgentRequest("attachments.write", "PUT", `/attachments/${segment(attachmentId)}/chunks/${index}`, input);
28
28
  /** Backend-to-backend transport. The authorizer talks to Core; only its scoped token reaches the provider. */
@@ -108,7 +108,25 @@ export class AgentClient {
108
108
  this.checkSnapshot(value, runId);
109
109
  return value;
110
110
  }
111
+ async closure(runId, options) {
112
+ const value = await this.get("runs.closure", `/runs/${segment(runId)}/closure`, options, { runId });
113
+ validateAgentRunClosure(value);
114
+ if (value.ref.id !== runId || !sameProvider(this.options.provider, value.ref.provider)
115
+ || value.pendingContinuations?.some(c => !sameProvider(this.options.provider, c.run.provider)))
116
+ throw new AgentApiError("response_invalid", "The closure belongs to another attempt or provider.", 502);
117
+ return value;
118
+ }
119
+ async discardDelivery(runId, requestId, options) {
120
+ const command = prepareAgentRequest("runs.discard", "PUT", `/runs/${segment(runId)}/discard`, { requestId }, { runId });
121
+ const value = await this.execute(command, options);
122
+ if (value?.requestId !== requestId || value.runId !== runId || value.state !== "discarded")
123
+ throw new AgentApiError("response_invalid", "The provider returned a different discard receipt.", 502);
124
+ return value;
125
+ }
111
126
  respond(runId, input, options) { return this.execute(prepareAgentResponse(runId, input), options); }
127
+ stop(runId, requestId = runId, options) {
128
+ return this.cancel(runId, { requestId }, options);
129
+ }
112
130
  cancel(runId, input, options) { return this.execute(prepareAgentCancel(runId, input), options); }
113
131
  control(runId, requestId, options) { return this.get("runs.controls.read", `/runs/${segment(runId)}/controls/${segment(requestId)}`, options, { runId }); }
114
132
  runControl(runId, input, options) { return this.execute(prepareAgentControl(runId, input), options); }
@@ -304,6 +322,7 @@ async function historyResponse(options, accept, page, endpoint, parameters) {
304
322
  url.searchParams.set("limit", String(page.limit));
305
323
  }
306
324
  const response = await (options.fetch ?? globalThis.fetch)(url, {
325
+ method: endpoint === "ack" ? "POST" : "GET",
307
326
  headers: { accept, authorization: `Bearer ${options.token}` },
308
327
  signal: options.signal, redirect: "error", cache: "no-store",
309
328
  });
@@ -410,8 +429,7 @@ export async function* watchLiveAgentHistory(options) {
410
429
  if (frame.event !== "observation")
411
430
  throw new AgentApiError("event_invalid", "Unexpected live history frame.", 502);
412
431
  const observation = historyObservation(value, frame.id, options.provider);
413
- const transient = observation.item.kind === "event" && ["message.delta", "tool.output"].includes(observation.item.event.type);
414
- if (!observation.epoch || transient !== (observation.sessionPosition === undefined))
432
+ if (!observation.epoch || !historyPosition(observation.sessionPosition))
415
433
  throw new AgentApiError("event_invalid", "Invalid live record position.", 502);
416
434
  yield observation;
417
435
  }
@@ -423,6 +441,14 @@ export async function* watchLiveAgentHistory(options) {
423
441
  if (!ready)
424
442
  throw new AgentApiError("stream_closed", "The stream closed before its live boundary.", 503, true);
425
443
  }
444
+ export async function acknowledgeAgentHistory(options, receipt) {
445
+ if (!historyIdentity(receipt.sessionId) || !historyIdentity(receipt.epoch) || !historyPosition(receipt.through))
446
+ throw new AgentApiError("invalid_input", "Invalid durable history receipt.", 400);
447
+ const response = await historyResponse({ ...options, cursor: undefined }, "application/json", undefined, "ack", receipt);
448
+ const value = JSON.parse(await boundedText(response, 1024));
449
+ if (!historyObject(value) || value.through !== receipt.through)
450
+ throw new AgentApiError("response_invalid", "Invalid history acknowledgement.", 502);
451
+ }
426
452
  export async function readAgentHistoryStates(options) {
427
453
  const response = await historyResponse({ ...options, cursor: undefined }, "application/json", options, "states", { afterSession: options.afterSession });
428
454
  const page = JSON.parse(await boundedText(response, 2 * MAX_BYTES + 32768));
@@ -461,8 +487,7 @@ export async function readAgentHistoryRange(options) {
461
487
  throw new AgentApiError("response_invalid", "Invalid session history range page.", 502);
462
488
  const observations = page.observations.map((value, index) => {
463
489
  const item = historyObservation(value, value?.cursor, options.provider);
464
- if (item.sessionId !== sessionId || item.epoch !== epoch || item.sessionPosition !== from + index || item.sessionPosition > to
465
- || item.item.kind === "event" && ["message.delta", "tool.output"].includes(item.item.event.type))
490
+ if (item.sessionId !== sessionId || item.epoch !== epoch || item.sessionPosition !== from + index || item.sessionPosition > to)
466
491
  throw new AgentApiError("response_invalid", "Invalid durable session record or range ordering.", 502);
467
492
  return item;
468
493
  });
@@ -47,7 +47,9 @@ export const AGENT_SCHEMAS = {
47
47
  DecisionResponse: { oneOf: [object({ kind: { const: "approval" }, decision: { enum: ["allow", "deny"] }, message: { type: "string", maxLength: 65536 } }, ["kind", "decision"]),
48
48
  object({ kind: { const: "question" }, answers: { type: "object", maxProperties: 128, propertyNames: id, additionalProperties: { oneOf: [{ type: "string", maxLength: 65536 }, list({ type: "string", maxLength: 65536 }, 128)] } } })] },
49
49
  ResponseInput: object({ ...baseControl, decisionId: id, decisionRevision: revision, response: ref("DecisionResponse") }),
50
- CancelInput: { oneOf: [object(baseControl), object({ requestId: uuid, fenceIfNotAdmitted: object({ sessionId: id, startDigest: digest }) })] },
50
+ DiscardInput: object({ requestId: uuid }),
51
+ DiscardReceipt: object({ requestId: uuid, runId: uuid, state: { const: "discarded" } }),
52
+ CancelInput: { oneOf: [object({ requestId: uuid }), object(baseControl), object({ requestId: uuid, fenceIfNotAdmitted: object({ sessionId: id, startDigest: digest }) })] },
51
53
  ControlInput: { oneOf: [
52
54
  object({ ...baseControl, command: { const: "park" }, decisionId: id, decisionRevision: revision, reason: text(8192) }, [...Object.keys(baseControl), "command", "decisionId", "decisionRevision"]),
53
55
  object({ ...baseControl, command: { const: "barrier" }, barrierId: id, kind: { enum: ["task_adoption", "child_wait", "source_rebind", "limits", "human_input"] }, generation: revision, acknowledgedSequence: sequence, snapshot: text(8192) }, [...Object.keys(baseControl), "command", "barrierId", "kind", "generation", "acknowledgedSequence"]),
@@ -68,7 +70,7 @@ export const AGENT_SCHEMAS = {
68
70
  Tool: object({ id, source: ref("Source"), name: text(), input: {}, output: { type: "string", maxLength: 1048576 }, state: { enum: ["running", "completed", "failed", "cancelled", "unknown"] }, truncated: boolean,
69
71
  command: object({ status: { enum: ["completed", "failed", "cancelled", "unknown"] }, exitCode: { type: "integer" }, durationMs: { type: "integer", minimum: 0 }, summary: text(65536) }, ["status"]) }, ["id", "name", "state"], true),
70
72
  RunSnapshot: object({ ref: ref("QualifiedRef"), sessionId: id, generation: uuid, revision: sequence,
71
- state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, freshness: { enum: ["current", "last_known", "unavailable"] }, observedAt: { type: "string", format: "date-time" },
73
+ state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, writerScopeClosed: boolean, freshness: { enum: ["current", "last_known", "unavailable"] }, observedAt: { type: "string", format: "date-time" },
72
74
  configurationRevision: revision, lastSequence: sequence, cursor: text(8192), pending: list(ref("PendingDecision"), 256),
73
75
  effects: object({ certainty: { enum: ["known", "unknown"] }, unresolvedCallIds: unique(id, 1024) }), result: ref("Result"), messages: list(ref("Message"), 4096), tools: list(ref("Tool"), 4096),
74
76
  agents: list(ref("ChildAgent"), 1024),
@@ -81,7 +83,7 @@ export const AGENT_SCHEMAS = {
81
83
  pendingContinuations: list(object({ requestId: uuid, run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }), 256) }, ["ref", "sessionId", "generation", "revision", "state", "phase", "stopConfirmed", "freshness", "observedAt", "configurationRevision", "lastSequence", "cursor", "pending", "effects"], true),
82
84
  HistoryObservation: object(historyObservation),
83
85
  LiveHistoryReady: object({ through: text(8192) }),
84
- LiveHistoryObservation: object({ ...historyObservation, epoch: uuid, sessionPosition: positive, sourceHistoryIncomplete: { const: true } }, [...Object.keys(historyObservation), "epoch"]),
86
+ LiveHistoryObservation: object({ ...historyObservation, epoch: uuid, sessionPosition: positive, sourceHistoryIncomplete: { const: true } }, [...Object.keys(historyObservation), "epoch", "sessionPosition"]),
85
87
  HistoryStates: object({ through: text(8192), nextSession: nullableText, sessions: list(object({
86
88
  sessionId: id, userId: text(512), principalId: text(512), epoch: uuid, head: positive, snapshot: ref("RunSnapshot"), sourceHistoryIncomplete: { const: true },
87
89
  }, ["sessionId", "userId", "principalId", "epoch", "head", "snapshot"]), 100) }),
@@ -92,13 +94,17 @@ export const AGENT_SCHEMAS = {
92
94
  Session: object({ ref: ref("QualifiedRef"), revision, configurationRevision: revision, configurationDigest: digest,
93
95
  nativeState: { enum: ["not_created", "available", "missing", "unavailable", "unknown"] }, activeRun: { oneOf: [ref("QualifiedRef"), { type: "null" }] },
94
96
  resolvedSkills: list(object({ skillId: digest, digest }), 202), configuration: ref("Configuration"), correlation: object({ conversation: ref("QualifiedRef"), task: ref("QualifiedRef") }, []) }, ["ref", "revision", "configurationRevision", "configurationDigest", "nativeState", "activeRun", "resolvedSkills"], true),
97
+ Closure: object({ ref: ref("QualifiedRef"), sessionId: id, generation: uuid, revision: sequence,
98
+ state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, writerScopeClosed: boolean,
99
+ pendingContinuations: list(object({ requestId: uuid, run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }), 256)
100
+ }, ["ref", "sessionId", "generation", "revision", "state", "phase", "stopConfirmed"]),
95
101
  ControlReceipt: object({ requestId: uuid, state: { enum: ["accepted", "applied", "rejected", "superseded", "unknown"] }, run: ref("QualifiedRef"), revision: sequence, generation: uuid, error: ref("ErrorDetail"),
96
102
  continuation: object({ run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }) }, ["requestId", "state", "run", "revision"], true),
97
103
  ErrorDetail: object({ code: text(), message: { type: "string", maxLength: 8192 }, retryable: boolean, requestId: uuid, details: { type: "object", additionalProperties: true } }, ["code", "message", "retryable"], true),
98
104
  Error: object({ error: ref("ErrorDetail") }),
99
105
  Connection: object({ id, revision, name: text(), ready: boolean, reason: text(8192), capabilities: capability }, ["id", "revision", "name", "ready"], true),
100
106
  ModelCatalog: object({ revision: text(256), models: list(object({ id: text(), name: text(), reasoningEfforts: list(nullableText), defaultReasoningEffort: nullableText, capabilities: capability, unavailableReason: text(8192) }, ["id", "reasoningEfforts"], true), 1000), defaultModel: nullableText, nextCursor: { type: ["string", "null"], maxLength: 8192 } }, ["revision", "models", "defaultModel"], true),
101
- Capabilities: object({ version: { const: 1 }, eventVersions: unique(text(), 16), capabilities: capability,
107
+ Capabilities: object({ version: { const: 2 }, eventVersions: unique(text(), 16), capabilities: capability,
102
108
  limits: object({ maxCommandBytes: positive, maxEventBytes: positive, maxSnapshotBytes: positive, maxReplayBytes: positive, replayRetentionMs: positive, maxControls: positive, maxPageSize: positive, maxDurationMs: positive, maxSkillSnapshotBytes: positive, maxSkillSnapshotFiles: positive }, ["maxCommandBytes", "maxEventBytes", "maxSnapshotBytes", "maxReplayBytes", "replayRetentionMs", "maxControls", "maxPageSize"], true), configuration: object({ resumeCompatible: unique(text(), 32) }) }, ["version", "eventVersions", "capabilities", "limits", "configuration"], true),
103
109
  };
104
110
  const eventNames = ["run.updated", "session.bound", "selection.updated", "message.started", "message.delta", "message.completed", "tool.started", "tool.output", "tool.completed", "decision.requested", "decision.updated", "decision.resolved", "control.updated", "result.available", "usage.updated", "context.updated", "agent.updated", "warning", "extension"];
@@ -129,13 +135,17 @@ const historySecurity = [{ installationHistory: [] }];
129
135
  const historyParam = (name, schema, required = false) => ({ name, in: "query", schema, required });
130
136
  const pageLimit = historyParam("limit", { type: "integer", minimum: 1, maximum: 100 });
131
137
  export const AGENT_OPENAPI = {
132
- openapi: "3.1.0", info: { title: "Hosty Agent Execution API", version: "1.0.0", description: "Independent provider execution. Paths are relative to the current Core-declared interface base. Exact UTF-8 command bytes and stable mutation UUIDs are retained across retries. No Harness dependency or raw native session IDs." },
138
+ openapi: "3.1.0", info: { title: "Hosty Agent Execution API", version: "2.0.0", description: "Independent provider execution. Paths are relative to the current Core-declared interface base. Exact UTF-8 command bytes and stable mutation UUIDs are retained across retries. No Harness dependency or raw native session IDs." },
133
139
  paths: {
134
140
  "/history/live": { get: { operationId: "history.live", security: historySecurity, parameters: [historyParam("after", text(8192))],
135
141
  description: "Open a fresh live subscription. The optional previous cursor checks archive ancestry. The ready event returns the subscribed boundary. Subsequent observation events carry an SSE id and every durable record carries its session position.",
136
142
  responses: { ...errors, "200": { description: "Ready boundary followed by live observations.", content: {
137
143
  "text/event-stream": { schema: { type: "string" }, "x-event-schemas": { ready: ref("LiveHistoryReady"), observation: ref("LiveHistoryObservation") } },
138
144
  } } } } },
145
+ "/history/ack": { post: { operationId: "history.ack", security: historySecurity,
146
+ description: "Commit the receiver's contiguous durable session position. Requires explicit acknowledgement authority for the consuming installation.",
147
+ parameters: [historyParam("sessionId", id, true), historyParam("epoch", uuid, true), historyParam("through", positive, true)],
148
+ responses: { ...errors, "200": { description: "Acknowledged contiguous position.", content: { "application/json": { schema: object({ through: positive }) } } } } } },
139
149
  "/history/states": { get: { operationId: "history.states", security: historySecurity,
140
150
  parameters: [historyParam("through", text(8192)), historyParam("afterSession", id), pageLimit],
141
151
  description: "List sessions with retained runs and their state and durable session head at the supplied or current installation boundary. Pass the returned boundary on later pages.",
@@ -163,7 +173,9 @@ export const AGENT_OPENAPI = {
163
173
  description: "At-least-once SSE. after and Last-Event-ID must agree. Persisted Event envelopes use event: agent and an opaque id cursor. 410 replay_expired requires installing a fresh atomic snapshot before following its cursor. Disconnect never cancels execution.",
164
174
  responses: { ...errors, "200": { description: "Persisted agent event stream.", content: { "text/event-stream": { schema: { type: "string" }, "x-event-schema": ref("Event") } } } } } },
165
175
  "/runs/{runId}/responses": { post: operation("runs.respond", "ControlReceipt", "ResponseInput", ["runId"], [200, 202]) },
166
- "/runs/{runId}/cancel": { post: operation("runs.cancel", "ControlReceipt", "CancelInput", ["runId"], [200, 202]) },
176
+ "/runs/{runId}/closure": { get: operation("runs.closure", "Closure", undefined, ["runId"]) },
177
+ "/runs/{runId}/discard": { put: operation("runs.discard", "DiscardReceipt", "DiscardInput", ["runId"]) },
178
+ "/runs/{runId}/stop": { put: operation("runs.cancel", "ControlReceipt", "CancelInput", ["runId"], [200, 202]) },
167
179
  "/runs/{runId}/controls": { post: { ...operation("runs.control", "ControlReceipt", "ControlInput", ["runId"], [200, 202]), description: "Optional controls require their advertised capabilities. Reconcile input is an attestation, never proof of actual native exit. Retirement requires provider-owned evidence of native process exit. Its applied receipt records retirement of the exact run and preserves unresolved tool outcomes." } },
168
180
  "/runs/{runId}/controls/{requestId}": { get: operation("runs.controls.read", "ControlReceipt", undefined, ["runId", "requestId"]) },
169
181
  }, components: { securitySchemes: { installationHistory: { type: "http", scheme: "bearer", description: "Core-issued installation history credential." }, coreOperation: { type: "http", scheme: "bearer", description: "Fresh Core exact-operation credential, never the caller's service/user token." } }, schemas: AGENT_SCHEMAS },
@@ -27,6 +27,11 @@ export type AgentParsedRequest = AgentParsedBase & ({
27
27
  } | {
28
28
  operation: "runs.respond";
29
29
  input: AgentResponseInput;
30
+ } | {
31
+ operation: "runs.discard";
32
+ input: {
33
+ requestId: string;
34
+ };
30
35
  } | {
31
36
  operation: "runs.cancel";
32
37
  input: AgentCancelInput;
@@ -37,7 +42,7 @@ export type AgentParsedRequest = AgentParsedBase & ({
37
42
  operation: "attachments.write";
38
43
  input: AgentAttachmentChunk;
39
44
  } | {
40
- operation: Exclude<AgentOperation, "sessions.create" | "sessions.configure" | "runs.start" | "runs.respond" | "runs.cancel" | "runs.control" | "attachments.write">;
45
+ operation: Exclude<AgentOperation, "sessions.create" | "sessions.configure" | "runs.start" | "runs.respond" | "runs.cancel" | "runs.discard" | "runs.control" | "attachments.write">;
41
46
  input: undefined;
42
47
  });
43
48
  export declare function validateAgentMcpSelection(value: unknown): asserts value is AgentMcpSelection;
@@ -54,6 +59,7 @@ export declare function validateAgentRunControlInput(value: unknown): asserts va
54
59
  export declare function validateAgentRequest(method: string, path: string, body: string | Uint8Array, expectedOperation?: AgentOperation): AgentParsedRequest;
55
60
  export declare function agentReplayCursor(after?: string | null, lastEventId?: string | null): string | undefined;
56
61
  export declare function validateAgentPendingDecision(value: unknown): asserts value is AgentPendingDecision;
62
+ export declare function validateAgentRunClosure(value: unknown): asserts value is import("./agent.js").AgentRunClosure;
57
63
  export declare function validateAgentRunSnapshot(value: unknown): asserts value is AgentRunSnapshot;
58
64
  export declare function validateAgentEvent(value: unknown): asserts value is AgentEvent;
59
65
  export declare function validateAgentCapabilities(value: unknown): asserts value is AgentCapabilities;
@@ -254,7 +254,7 @@ export function validateAgentCancelInput(value) {
254
254
  if (!opaque(value.fenceIfNotAdmitted.sessionId) || !digest(value.fenceIfNotAdmitted.startDigest) || value.expectedRevision !== undefined || value.expectedGeneration !== undefined)
255
255
  fail("A delayed-start fence requires only the exact intended session/digest.");
256
256
  }
257
- else
257
+ else if (value.expectedRevision !== undefined || value.expectedGeneration !== undefined)
258
258
  controlBase(value);
259
259
  }
260
260
  /** This validates an attestation's shape only. Providers must independently confirm actual native exit. */
@@ -286,7 +286,7 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
286
286
  const url = new URL(path, "http://agent.invalid"), route = url.pathname, query = {};
287
287
  let operation, sessionId, runId, requestId, connectionId, attachmentId, chunkIndex;
288
288
  const attachment = /^\/attachments\/([A-Za-z0-9_-]{1,256})\/chunks\/(0|[1-9][0-9]?)$/.exec(route);
289
- const match = /^\/(sessions|runs|connections)(?:\/([A-Za-z0-9_-]{1,256}))?(?:\/(configurations|runs|events|responses|cancel|controls|models|usage))?(?:\/([A-Za-z0-9_-]{1,256}))?$/.exec(route);
289
+ const match = /^\/(sessions|runs|connections)(?:\/([A-Za-z0-9_-]{1,256}))?(?:\/(configurations|runs|events|closure|discard|responses|stop|controls|models|usage))?(?:\/([A-Za-z0-9_-]{1,256}))?$/.exec(route);
290
290
  if (route === "/capabilities" && method === "GET")
291
291
  operation = "capabilities";
292
292
  else if (attachment && method === "PUT") {
@@ -319,11 +319,15 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
319
319
  runId = id;
320
320
  if (!sub && method === "GET")
321
321
  operation = "runs.read";
322
+ else if (sub === "closure" && !child && method === "GET")
323
+ operation = "runs.closure";
322
324
  else if (sub === "events" && !child && method === "GET")
323
325
  operation = "runs.events";
324
326
  else if (sub === "responses" && !child && method === "POST")
325
327
  operation = "runs.respond";
326
- else if (sub === "cancel" && !child && method === "POST")
328
+ else if (sub === "discard" && !child && method === "PUT")
329
+ operation = "runs.discard";
330
+ else if (sub === "stop" && !child && method === "PUT")
327
331
  operation = "runs.cancel";
328
332
  else if (sub === "controls" && !child && method === "POST")
329
333
  operation = "runs.control";
@@ -343,7 +347,7 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
343
347
  }
344
348
  }
345
349
  if (!operation || expectedOperation !== undefined && expectedOperation !== operation)
346
- fail("Use a declared agent v1 operation.", 422, "unsupported_operation");
350
+ fail("Use a declared agent v2 operation.", 422, "unsupported_operation");
347
351
  const allowed = operation === "runs.events" ? ["after"] : ["sessions.list", "connections.list"].includes(operation) ? ["cursor", "limit"] : [];
348
352
  for (const [key, value] of url.searchParams) {
349
353
  if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1)
@@ -387,6 +391,11 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
387
391
  validateAgentRunInput(input);
388
392
  else if (operation === "runs.respond")
389
393
  validateAgentResponseInput(input);
394
+ else if (operation === "runs.discard") {
395
+ shape(input, ["requestId"], "delivery discard");
396
+ if (!uuid(input.requestId))
397
+ fail("A discard request UUID is required.");
398
+ }
390
399
  else if (operation === "runs.cancel")
391
400
  validateAgentCancelInput(input);
392
401
  else if (operation === "runs.control")
@@ -443,6 +452,25 @@ export function validateAgentPendingDecision(value) {
443
452
  }
444
453
  }
445
454
  }
455
+ export function validateAgentRunClosure(value) {
456
+ if (!object(value))
457
+ responseProblem("Missing execution closure.");
458
+ qualified(value.ref);
459
+ if (!opaque(value.sessionId) || !uuid(value.generation) || !decimal(value.revision, true) || typeof value.stopConfirmed !== "boolean"
460
+ || value.writerScopeClosed !== undefined && (typeof value.writerScopeClosed !== "boolean" || value.writerScopeClosed && !value.stopConfirmed)
461
+ || !["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"].includes(String(value.state))
462
+ || !["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"].includes(String(value.phase))
463
+ || ["succeeded", "failed", "cancelled"].includes(String(value.state)) && !value.stopConfirmed)
464
+ responseProblem("Invalid execution closure.");
465
+ if (value.pendingContinuations !== undefined) {
466
+ array(value.pendingContinuations, 256, "continuation references");
467
+ for (const item of value.pendingContinuations) {
468
+ if (!object(item) || !uuid(item.requestId) || !["pending", "awaiting_authorization", "admitted", "superseded"].includes(String(item.state)))
469
+ responseProblem("Invalid continuation receipt.");
470
+ qualified(item.run);
471
+ }
472
+ }
473
+ }
446
474
  export function validateAgentRunSnapshot(value) {
447
475
  if (!object(value))
448
476
  responseProblem("A run snapshot is required.");
@@ -450,7 +478,8 @@ export function validateAgentRunSnapshot(value) {
450
478
  if (!opaque(value.sessionId) || !uuid(value.generation) || !decimal(value.revision, true) || !decimal(value.configurationRevision) || !decimal(value.lastSequence, true)
451
479
  || !["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"].includes(String(value.state))
452
480
  || !["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"].includes(String(value.phase))
453
- || typeof value.stopConfirmed !== "boolean" || !["current", "last_known", "unavailable"].includes(String(value.freshness)) || !bounded(value.observedAt) || !Number.isFinite(Date.parse(value.observedAt)) || !bounded(value.cursor, 8192)
481
+ || typeof value.stopConfirmed !== "boolean"
482
+ || value.writerScopeClosed !== undefined && (typeof value.writerScopeClosed !== "boolean" || value.writerScopeClosed && !value.stopConfirmed) || !["current", "last_known", "unavailable"].includes(String(value.freshness)) || !bounded(value.observedAt) || !Number.isFinite(Date.parse(value.observedAt)) || !bounded(value.cursor, 8192)
454
483
  || !Array.isArray(value.pending) || value.pending.length > 256 || !object(value.effects) || !["known", "unknown"].includes(String(value.effects.certainty)))
455
484
  responseProblem("Invalid atomic run snapshot.");
456
485
  for (const decision of value.pending)
@@ -572,7 +601,7 @@ export function validateAgentEvent(value) {
572
601
  responseProblem("Event byte allowance exceeded.");
573
602
  }
574
603
  export function validateAgentCapabilities(value) {
575
- if (!object(value) || value.version !== 1 || !Array.isArray(value.eventVersions) || !value.eventVersions.includes(AGENT_EVENT_VERSION) || !object(value.limits) || !object(value.configuration))
604
+ if (!object(value) || value.version !== 2 || !Array.isArray(value.eventVersions) || !value.eventVersions.includes(AGENT_EVENT_VERSION) || !object(value.limits) || !object(value.configuration))
576
605
  responseProblem("Unsupported agent contract.");
577
606
  strings(value.capabilities, 128);
578
607
  strings(value.configuration.resumeCompatible, 32);
@@ -33,6 +33,7 @@ export type AgentRun = {
33
33
  observedAt: string;
34
34
  freshness: "current" | "last_known" | "unavailable";
35
35
  stopConfirmed: boolean;
36
+ writerScopeClosed?: boolean;
36
37
  nativeSession?: NativeSessionRef | null;
37
38
  conversation?: ConversationRef | null;
38
39
  };
package/dist/agent.d.ts CHANGED
@@ -46,7 +46,7 @@ export type AgentLimits = {
46
46
  maxSkillSnapshotFiles?: number;
47
47
  };
48
48
  export type AgentCapabilities = {
49
- version: 1;
49
+ version: 2;
50
50
  eventVersions: string[];
51
51
  capabilities: AgentCapability[];
52
52
  limits: AgentLimits;
@@ -308,7 +308,10 @@ export type AgentRunSnapshot = {
308
308
  revision: Revision;
309
309
  state: AgentRunState;
310
310
  phase: AgentRunPhase;
311
+ /** The observed root agent has exited or was fenced before launch. */
311
312
  stopConfirmed: boolean;
313
+ /** Whether a qualified writer scope has closed. Omitted when the provider has no such evidence. */
314
+ writerScopeClosed?: boolean;
312
315
  freshness: "current" | "last_known" | "unavailable";
313
316
  observedAt: string;
314
317
  configurationRevision: Revision;
@@ -368,6 +371,12 @@ export type AgentRunSnapshot = {
368
371
  state: "pending" | "awaiting_authorization" | "admitted" | "superseded";
369
372
  }>;
370
373
  };
374
+ export type AgentDiscardReceipt = {
375
+ requestId: string;
376
+ runId: string;
377
+ state: "discarded";
378
+ };
379
+ export type AgentRunClosure = Pick<AgentRunSnapshot, "ref" | "sessionId" | "generation" | "revision" | "state" | "phase" | "stopConfirmed" | "writerScopeClosed" | "pendingContinuations">;
371
380
  export type AgentApprovalResponse = {
372
381
  kind: "approval";
373
382
  decision: "allow" | "deny";
@@ -388,6 +397,10 @@ export type AgentResponseInput = {
388
397
  export type AgentCancelInput = {
389
398
  requestId: string;
390
399
  } & ({
400
+ expectedGeneration?: never;
401
+ expectedRevision?: never;
402
+ fenceIfNotAdmitted?: never;
403
+ } | {
391
404
  expectedGeneration: string;
392
405
  expectedRevision: Revision;
393
406
  fenceIfNotAdmitted?: never;
@@ -503,7 +516,7 @@ export declare class AgentApiError extends Error {
503
516
  readonly requestId?: string | undefined;
504
517
  constructor(code: string, message: string, status: number, retryable?: boolean, details?: Record<string, unknown> | undefined, requestId?: string | undefined);
505
518
  }
506
- export type AgentOperation = "capabilities" | "connections.list" | "connections.models" | "connections.usage" | "attachments.write" | "sessions.create" | "sessions.configure" | "sessions.read" | "sessions.list" | "runs.start" | "runs.read" | "runs.events" | "runs.respond" | "runs.cancel" | "runs.control" | "runs.controls.read";
519
+ export type AgentOperation = "capabilities" | "connections.list" | "connections.models" | "connections.usage" | "attachments.write" | "sessions.create" | "sessions.configure" | "sessions.read" | "sessions.list" | "runs.start" | "runs.read" | "runs.closure" | "runs.discard" | "runs.events" | "runs.respond" | "runs.cancel" | "runs.control" | "runs.controls.read";
507
520
  /** Core transport names for the optional consumer-bound task workflow, without general Core tools. */
508
521
  export declare const AGENT_SESSION_WORKFLOW_TOOLS: readonly ["task_executor_options", "task_options", "task_list", "task_get", "task_create", "task_edit", "task_action", "task_result", "task_fail", "task_request_input", "task_adopt", "task_prepare_executor", "task_delegate", "task_wait", "task_plan", "task_bind_workspace", "task_execution_get"];
509
522
  /** Optional business workflow owned by the invoking consumer, separate from native execution. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hosty-sdk/app",
3
- "version": "0.55.0",
3
+ "version": "0.56.0",
4
4
  "description": "Hosty app auth: session state machine, recovery bridge, Core revalidation, and the embedder responder.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
@@ -824,8 +824,56 @@
824
824
  ],
825
825
  "additionalProperties": false
826
826
  },
827
+ "DiscardInput": {
828
+ "type": "object",
829
+ "properties": {
830
+ "requestId": {
831
+ "type": "string",
832
+ "format": "uuid"
833
+ }
834
+ },
835
+ "required": [
836
+ "requestId"
837
+ ],
838
+ "additionalProperties": false
839
+ },
840
+ "DiscardReceipt": {
841
+ "type": "object",
842
+ "properties": {
843
+ "requestId": {
844
+ "type": "string",
845
+ "format": "uuid"
846
+ },
847
+ "runId": {
848
+ "type": "string",
849
+ "format": "uuid"
850
+ },
851
+ "state": {
852
+ "const": "discarded"
853
+ }
854
+ },
855
+ "required": [
856
+ "requestId",
857
+ "runId",
858
+ "state"
859
+ ],
860
+ "additionalProperties": false
861
+ },
827
862
  "CancelInput": {
828
863
  "oneOf": [
864
+ {
865
+ "type": "object",
866
+ "properties": {
867
+ "requestId": {
868
+ "type": "string",
869
+ "format": "uuid"
870
+ }
871
+ },
872
+ "required": [
873
+ "requestId"
874
+ ],
875
+ "additionalProperties": false
876
+ },
829
877
  {
830
878
  "type": "object",
831
879
  "properties": {
@@ -1514,6 +1562,9 @@
1514
1562
  "stopConfirmed": {
1515
1563
  "type": "boolean"
1516
1564
  },
1565
+ "writerScopeClosed": {
1566
+ "type": "boolean"
1567
+ },
1517
1568
  "freshness": {
1518
1569
  "enum": [
1519
1570
  "current",
@@ -1944,7 +1995,8 @@
1944
1995
  "principalId",
1945
1996
  "userId",
1946
1997
  "item",
1947
- "epoch"
1998
+ "epoch",
1999
+ "sessionPosition"
1948
2000
  ],
1949
2001
  "additionalProperties": false
1950
2002
  },
@@ -2335,6 +2387,95 @@
2335
2387
  ],
2336
2388
  "additionalProperties": true
2337
2389
  },
2390
+ "Closure": {
2391
+ "type": "object",
2392
+ "properties": {
2393
+ "ref": {
2394
+ "$ref": "#/$defs/QualifiedRef"
2395
+ },
2396
+ "sessionId": {
2397
+ "type": "string",
2398
+ "pattern": "^[A-Za-z0-9_-]{1,256}$"
2399
+ },
2400
+ "generation": {
2401
+ "type": "string",
2402
+ "format": "uuid"
2403
+ },
2404
+ "revision": {
2405
+ "type": "string",
2406
+ "pattern": "^(0|[1-9][0-9]{0,39})$"
2407
+ },
2408
+ "state": {
2409
+ "enum": [
2410
+ "queued",
2411
+ "running",
2412
+ "waiting_for_input",
2413
+ "succeeded",
2414
+ "failed",
2415
+ "cancelled",
2416
+ "unknown"
2417
+ ]
2418
+ },
2419
+ "phase": {
2420
+ "enum": [
2421
+ "preparing",
2422
+ "executing",
2423
+ "waiting",
2424
+ "finalizing",
2425
+ "cancelling",
2426
+ "parked",
2427
+ "interrupted",
2428
+ "terminal"
2429
+ ]
2430
+ },
2431
+ "stopConfirmed": {
2432
+ "type": "boolean"
2433
+ },
2434
+ "writerScopeClosed": {
2435
+ "type": "boolean"
2436
+ },
2437
+ "pendingContinuations": {
2438
+ "type": "array",
2439
+ "maxItems": 256,
2440
+ "items": {
2441
+ "type": "object",
2442
+ "properties": {
2443
+ "requestId": {
2444
+ "type": "string",
2445
+ "format": "uuid"
2446
+ },
2447
+ "run": {
2448
+ "$ref": "#/$defs/QualifiedRef"
2449
+ },
2450
+ "state": {
2451
+ "enum": [
2452
+ "pending",
2453
+ "awaiting_authorization",
2454
+ "admitted",
2455
+ "superseded"
2456
+ ]
2457
+ }
2458
+ },
2459
+ "required": [
2460
+ "requestId",
2461
+ "run",
2462
+ "state"
2463
+ ],
2464
+ "additionalProperties": false
2465
+ }
2466
+ }
2467
+ },
2468
+ "required": [
2469
+ "ref",
2470
+ "sessionId",
2471
+ "generation",
2472
+ "revision",
2473
+ "state",
2474
+ "phase",
2475
+ "stopConfirmed"
2476
+ ],
2477
+ "additionalProperties": false
2478
+ },
2338
2479
  "ControlReceipt": {
2339
2480
  "type": "object",
2340
2481
  "properties": {
@@ -2574,7 +2715,7 @@
2574
2715
  "type": "object",
2575
2716
  "properties": {
2576
2717
  "version": {
2577
- "const": 1
2718
+ "const": 2
2578
2719
  },
2579
2720
  "eventVersions": {
2580
2721
  "type": "array",