@hosty-sdk/app 0.54.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
  };
@@ -1,6 +1,6 @@
1
1
  import { type AgentSessionWorkflowTool } from "./agent.js";
2
2
  export declare const workflowTools: (selected?: readonly AgentSessionWorkflowTool[]) => {
3
- name: "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" | "subagent_profiles" | "subagent_spawn" | "subagent_status" | "subagent_wait";
3
+ name: "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" | "subagent_profiles" | "subagent_spawn" | "subagent_status" | "subagent_wait" | "profile_list" | "profile_options" | "profile_create" | "profile_edit" | "skill_list" | "skill_discover" | "skill_install";
4
4
  description: string;
5
5
  inputSchema: {
6
6
  type: string;
@@ -1,4 +1,4 @@
1
- import { AGENT_SESSION_WORKFLOW_TOOLS, AGENT_SUBAGENT_WORKFLOW_TOOLS } from "./agent.js";
1
+ import { AGENT_PROFILE_MANAGEMENT_WORKFLOW_TOOLS, AGENT_SESSION_WORKFLOW_TOOLS, AGENT_SUBAGENT_WORKFLOW_TOOLS } from "./agent.js";
2
2
  const object = (properties, required = []) => ({ type: "object", properties, required, additionalProperties: false });
3
3
  const id = { type: "string", format: "uuid" }, revision = { type: "integer", minimum: 1 }, counter = { type: "integer", minimum: 0 };
4
4
  const text = (maxLength) => ({ type: "string", maxLength });
@@ -18,7 +18,20 @@ const result = object({ markdown: text(32000), resources }, ["markdown", "resour
18
18
  const requestId = { ...id, description: "A fresh globally unique UUID for a new operation. Never reuse sample IDs or IDs from another chat or task. Retain this exact UUID and input only when recovering the same operation." };
19
19
  const mutation = { requestId, expectedRevision: revision };
20
20
  const writeScope = object({ mode: { enum: ["read", "write", "exclusive"] }, paths: { type: "array", items: text(2000), maxItems: 100 } }, ["mode", "paths"]);
21
+ const optionalText = (maxLength) => ({ oneOf: [text(maxLength), { type: "null" }] });
22
+ const profileFields = {
23
+ name: text(100), description: text(2000), instructions: text(8000), connectionId: optionalText(128),
24
+ model: optionalText(256), reasoningEffort: optionalText(128), skillIds: { type: "array", items: text(64), maxItems: 202 },
25
+ };
26
+ const gitSkillSource = object({ repository: text(2048), ref: text(256), path: text(1024), connectionId: optionalText(200) }, ["repository"]);
21
27
  const schemas = {
28
+ "profile-list": object({ profileId: text(200) }),
29
+ "profile-options": object({ connectionId: text(128) }),
30
+ "profile-create": object({ expectedRevision: counter, profile: object(profileFields, ["name"]) }, ["expectedRevision", "profile"]),
31
+ "profile-edit": object({ profileId: text(200), expectedRevision: counter, changes: object(profileFields) }, ["profileId", "expectedRevision", "changes"]),
32
+ "skill-list": object({ includeSourceConnections: { type: "boolean" } }),
33
+ "skill-discover": object({ source: gitSkillSource }, ["source"]),
34
+ "skill-install": object({ source: gitSkillSource, commit: text(64), paths: { type: "array", items: text(1024), minItems: 1, maxItems: 200 } }, ["source", "commit", "paths"]),
22
35
  "subagent-profiles": object({}),
23
36
  "subagent-spawn": object({ requestId, profileId: text(200), profileRevision: revision, prompt: text(32000), title: text(200) }, ["requestId", "profileId", "profileRevision", "prompt"]),
24
37
  "subagent-status": object({ childSessionId: id }),
@@ -52,6 +65,13 @@ const schemas = {
52
65
  "task-execution-get": object({ cursor: text(200), limit: { type: "integer", minimum: 1, maximum: 100 } }),
53
66
  };
54
67
  const descriptions = {
68
+ "profile-list": "List saved profile summaries and the directory revision. Supply a profile ID to read its configuration.",
69
+ "profile-options": "List available connections. Supply one connection ID to read its model and reasoning choices.",
70
+ "profile-create": "Create a reusable profile at the current directory revision. Attach installed skills by their stable IDs.",
71
+ "profile-edit": "Edit the named fields of a reusable profile at the current directory revision. Read the stored configuration before editing.",
72
+ "skill-list": "List installed skill packages with stable IDs, descriptions and provenance. Set includeSourceConnections to see the operator's source connection IDs and labels for private Git repositories.",
73
+ "skill-discover": "Read skill candidates from a Git source. Use their descriptions for recommendations and retain the commit and exact paths for installation.",
74
+ "skill-install": "Install the selected package paths into the shared skill library at the commit returned by discovery. Use the returned stable IDs to attach them to profiles.",
55
75
  "subagent-profiles": "List saved agent profiles and their current revisions for a child chat.",
56
76
  "subagent-spawn": "Open a child chat with the selected profile and prompt. Reuse the request UUID only to recover this exact delegation.",
57
77
  "subagent-status": "Read the state and available results of this chat’s children. Supply a child session ID to inspect one.",
@@ -75,9 +95,9 @@ const descriptions = {
75
95
  "task-execution-get": "Read this session's task binding, root plan, limits and bounded child results. Before adoption, read the current session revisions and mode.",
76
96
  };
77
97
  /** Fixed business tools only. Their schemas grant no native, Core MCP or source authority. */
78
- const knownTools = [...AGENT_SESSION_WORKFLOW_TOOLS, ...AGENT_SUBAGENT_WORKFLOW_TOOLS];
98
+ const knownTools = [...AGENT_SESSION_WORKFLOW_TOOLS, ...AGENT_SUBAGENT_WORKFLOW_TOOLS, ...AGENT_PROFILE_MANAGEMENT_WORKFLOW_TOOLS];
79
99
  export const workflowTools = (selected = AGENT_SESSION_WORKFLOW_TOOLS) => knownTools.filter(name => selected.includes(name)).map(name => {
80
100
  const action = name.replaceAll("_", "-");
81
- return { name, description: descriptions[action], inputSchema: object(name.startsWith("subagent_") ? { input: schemas[action] } : { input: schemas[action], source: provider }, ["input"]),
82
- annotations: { readOnlyHint: ["subagent_profiles", "subagent_status", "task_executor_options", "task_options", "task_list", "task_get", "task_execution_get"].includes(name), destructiveHint: name === "task_action", openWorldHint: false } };
101
+ return { name, description: descriptions[action], inputSchema: object(name.startsWith("task_") ? { input: schemas[action], source: provider } : { input: schemas[action] }, ["input"]),
102
+ annotations: { readOnlyHint: ["profile_list", "profile_options", "skill_list", "skill_discover", "subagent_profiles", "subagent_status", "task_executor_options", "task_options", "task_list", "task_get", "task_execution_get"].includes(name), destructiveHint: name === "task_action", openWorldHint: name === "skill_discover" || name === "skill_install" } };
83
103
  });
package/dist/agent.d.ts CHANGED
@@ -30,6 +30,7 @@ export declare const AGENT_CAPABILITIES: {
30
30
  readonly mcpPolicy: "mcp.policy-update";
31
31
  readonly consumerWorkflow: "workflow.consumer";
32
32
  readonly sessionSubagents: "workflow.subagents";
33
+ readonly profileManagement: "workflow.profile-management";
33
34
  };
34
35
  export type AgentCapability = typeof AGENT_CAPABILITIES[keyof typeof AGENT_CAPABILITIES] | (string & {});
35
36
  export type AgentLimits = {
@@ -45,7 +46,7 @@ export type AgentLimits = {
45
46
  maxSkillSnapshotFiles?: number;
46
47
  };
47
48
  export type AgentCapabilities = {
48
- version: 1;
49
+ version: 2;
49
50
  eventVersions: string[];
50
51
  capabilities: AgentCapability[];
51
52
  limits: AgentLimits;
@@ -307,7 +308,10 @@ export type AgentRunSnapshot = {
307
308
  revision: Revision;
308
309
  state: AgentRunState;
309
310
  phase: AgentRunPhase;
311
+ /** The observed root agent has exited or was fenced before launch. */
310
312
  stopConfirmed: boolean;
313
+ /** Whether a qualified writer scope has closed. Omitted when the provider has no such evidence. */
314
+ writerScopeClosed?: boolean;
311
315
  freshness: "current" | "last_known" | "unavailable";
312
316
  observedAt: string;
313
317
  configurationRevision: Revision;
@@ -367,6 +371,12 @@ export type AgentRunSnapshot = {
367
371
  state: "pending" | "awaiting_authorization" | "admitted" | "superseded";
368
372
  }>;
369
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">;
370
380
  export type AgentApprovalResponse = {
371
381
  kind: "approval";
372
382
  decision: "allow" | "deny";
@@ -387,6 +397,10 @@ export type AgentResponseInput = {
387
397
  export type AgentCancelInput = {
388
398
  requestId: string;
389
399
  } & ({
400
+ expectedGeneration?: never;
401
+ expectedRevision?: never;
402
+ fenceIfNotAdmitted?: never;
403
+ } | {
390
404
  expectedGeneration: string;
391
405
  expectedRevision: Revision;
392
406
  fenceIfNotAdmitted?: never;
@@ -502,12 +516,14 @@ export declare class AgentApiError extends Error {
502
516
  readonly requestId?: string | undefined;
503
517
  constructor(code: string, message: string, status: number, retryable?: boolean, details?: Record<string, unknown> | undefined, requestId?: string | undefined);
504
518
  }
505
- 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";
506
520
  /** Core transport names for the optional consumer-bound task workflow, without general Core tools. */
507
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"];
508
522
  /** Optional business workflow owned by the invoking consumer, separate from native execution. */
509
523
  export declare const AGENT_SUBAGENT_WORKFLOW_TOOLS: readonly ["subagent_profiles", "subagent_spawn", "subagent_status", "subagent_wait"];
510
- export type AgentSessionWorkflowTool = typeof AGENT_SESSION_WORKFLOW_TOOLS[number] | typeof AGENT_SUBAGENT_WORKFLOW_TOOLS[number];
524
+ /** Profile and skill management is separately selected for an operator's conversation. */
525
+ export declare const AGENT_PROFILE_MANAGEMENT_WORKFLOW_TOOLS: readonly ["profile_list", "profile_options", "profile_create", "profile_edit", "skill_list", "skill_discover", "skill_install"];
526
+ export type AgentSessionWorkflowTool = typeof AGENT_SESSION_WORKFLOW_TOOLS[number] | typeof AGENT_SUBAGENT_WORKFLOW_TOOLS[number] | typeof AGENT_PROFILE_MANAGEMENT_WORKFLOW_TOOLS[number];
511
527
  export type AgentSessionWorkflowBinding = {
512
528
  executor: ProviderRef;
513
529
  sessionId: string;
package/dist/agent.js CHANGED
@@ -11,6 +11,7 @@ export const AGENT_CAPABILITIES = {
11
11
  predictions: "predictions", connectionUsage: "connections.usage",
12
12
  approvalMode: "configuration.approval-mode",
13
13
  mcpPolicy: "mcp.policy-update", consumerWorkflow: "workflow.consumer", sessionSubagents: "workflow.subagents",
14
+ profileManagement: "workflow.profile-management",
14
15
  };
15
16
  export class AgentApiError extends Error {
16
17
  code;
@@ -36,3 +37,7 @@ export const AGENT_SESSION_WORKFLOW_TOOLS = [
36
37
  ];
37
38
  /** Optional business workflow owned by the invoking consumer, separate from native execution. */
38
39
  export const AGENT_SUBAGENT_WORKFLOW_TOOLS = ["subagent_profiles", "subagent_spawn", "subagent_status", "subagent_wait"];
40
+ /** Profile and skill management is separately selected for an operator's conversation. */
41
+ export const AGENT_PROFILE_MANAGEMENT_WORKFLOW_TOOLS = [
42
+ "profile_list", "profile_options", "profile_create", "profile_edit", "skill_list", "skill_discover", "skill_install",
43
+ ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hosty-sdk/app",
3
- "version": "0.54.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",