@hosty-sdk/app 0.48.0 → 0.50.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.
@@ -1,4 +1,4 @@
1
- import { type AgentAttachment, type AgentAttachmentChunk, type AgentAttachmentChunkReceipt, type AgentAuthorizer, type AgentAuthorizationRequest, type AgentCancelInput, type AgentCapabilities, type AgentConfigurationCreate, type AgentConnectionPage, type AgentConnectionUsage, type AgentControlReceipt, type AgentEvent, type AgentModelCatalog, type AgentOperation, type AgentPreparedRequest, type AgentProviderRef, type AgentResponseInput, type AgentRunControlInput, type AgentRunInput, type AgentRunSnapshot, type AgentSession, type AgentSessionCreate, type AgentSessionPage, type AgentWatchItem } from "./agent.js";
1
+ import { type AgentAttachment, type AgentAttachmentChunk, type AgentAttachmentChunkReceipt, type AgentAuthorizer, type AgentAuthorizationRequest, type AgentCancelInput, type AgentCapabilities, type AgentConfigurationCreate, type AgentConnectionPage, type AgentConnectionUsage, type AgentControlReceipt, type AgentEvent, type AgentHistoryObservation, type AgentHistorySessionState, type AgentModelCatalog, type AgentOperation, type AgentPreparedRequest, type AgentProviderRef, type AgentResponseInput, type AgentRunControlInput, type AgentRunInput, type AgentRunSnapshot, type AgentSession, type AgentSessionCreate, type AgentSessionPage, type AgentWatchItem } from "./agent.js";
2
2
  export type AgentClientOptions = {
3
3
  provider: AgentProviderRef;
4
4
  authorize: AgentAuthorizer;
@@ -63,6 +63,7 @@ export declare class AgentClient {
63
63
  /** One authenticated stream; watchRun adds reconnect and atomic snapshot recovery. */
64
64
  events(runId: string, options?: AgentRequestOptions & {
65
65
  cursor?: string;
66
+ onRenewal?: () => void;
66
67
  }): AsyncGenerator<{
67
68
  event: AgentEvent;
68
69
  cursor: string;
@@ -70,9 +71,59 @@ export declare class AgentClient {
70
71
  /** Snapshot items replace consumer state; event items are new, deduplicated persisted events. */
71
72
  watchRun(runId: string, options?: AgentWatchOptions): AsyncGenerator<AgentWatchItem>;
72
73
  }
74
+ export type AgentHistoryOptions = {
75
+ url: string;
76
+ token: string;
77
+ provider?: AgentProviderRef;
78
+ cursor?: string;
79
+ signal?: AbortSignal;
80
+ fetch?: typeof fetch;
81
+ onOpen?: () => void | Promise<void>;
82
+ /** Silence between byte reads, including transport heartbeats, while the consumer is ready. */
83
+ idleTimeoutMs?: number;
84
+ };
85
+ export type AgentHistoryPage = {
86
+ observations: AgentHistoryObservation[];
87
+ through: string;
88
+ nextCursor: string | null;
89
+ };
90
+ type HistoryPageOptions = {
91
+ through?: string;
92
+ limit?: number;
93
+ };
94
+ /** Open one read-only installation subscription. Resume from the last durably applied position. */
95
+ export declare function watchAgentHistory(options: AgentHistoryOptions): AsyncGenerator<AgentHistoryObservation>;
96
+ /** Subscribe at the provider's current boundary. Supply a previous cursor to validate archive ancestry. */
97
+ export declare function watchLiveAgentHistory(options: AgentHistoryOptions & {
98
+ onReady: (boundary: string) => void | Promise<void>;
99
+ }): AsyncGenerator<AgentHistoryObservation>;
100
+ export declare function readAgentHistoryStates(options: AgentHistoryOptions & HistoryPageOptions & {
101
+ afterSession?: string;
102
+ }): Promise<{
103
+ through: string;
104
+ sessions: AgentHistorySessionState[];
105
+ nextSession: string | null;
106
+ }>;
107
+ export declare function readAgentHistoryRange(options: AgentHistoryOptions & {
108
+ through: string;
109
+ sessionId: string;
110
+ epoch: string;
111
+ from: number;
112
+ to: number;
113
+ limit?: number;
114
+ }): Promise<{
115
+ observations: AgentHistoryObservation[];
116
+ nextPosition: number | null;
117
+ }>;
118
+ /** Read a bounded page at a stable installation feed position. Pass through to subsequent pages. */
119
+ export declare function readAgentHistoryPage(options: AgentHistoryOptions & {
120
+ through?: string;
121
+ limit?: number;
122
+ }): Promise<AgentHistoryPage>;
73
123
  /** Streaming decoder handles split UTF-8, CR/LF framing, multi-line data and comment heartbeats. */
74
- export declare function parseAgentSse(response: Pick<Response, "body">, maxBytes?: number): AsyncGenerator<{
124
+ export declare function parseAgentSse(response: Pick<Response, "body">, maxBytes?: number, idleMs?: number): AsyncGenerator<{
75
125
  id: string;
76
126
  event: string;
77
127
  data: string;
78
128
  }>;
129
+ export {};
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { AgentApiError, } from "./agent.js";
3
- import { validateAgentEvent, validateAgentRunSnapshot, validateAgentRequest, validateAgentSession, validateAgentCapabilities, validateAgentControlReceipt } from "./agent-server.js";
3
+ import { agentReplayCursor, validateAgentEvent, 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) => {
@@ -200,6 +200,8 @@ export class AgentClient {
200
200
  if (!response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase().includes("text/event-stream"))
201
201
  throw new AgentApiError("response_invalid", "The provider did not return an event stream.", 502);
202
202
  for await (const frame of parseAgentSse(response, MAX_BYTES)) {
203
+ if (frame.event === "renew" && frame.data === "{}")
204
+ options.onRenewal?.();
203
205
  if (frame.event !== "agent")
204
206
  continue;
205
207
  let event;
@@ -221,7 +223,8 @@ export class AgentClient {
221
223
  async *watchRun(runId, options = {}) {
222
224
  let snapshot = await this.run(runId, options);
223
225
  yield { kind: "snapshot", snapshot };
224
- let cursor = snapshot.cursor, sequence = BigInt(snapshot.lastSequence), generation = snapshot.generation;
226
+ let cursor = snapshot.cursor, sequence = BigInt(snapshot.lastSequence);
227
+ const generation = snapshot.generation;
225
228
  let retries = 0;
226
229
  const max = options.maxReconnects ?? 5;
227
230
  if (!Number.isSafeInteger(max) || max < 0 || max > 100 || options.reconnectDelayMs !== undefined && (!Number.isSafeInteger(options.reconnectDelayMs) || options.reconnectDelayMs < 0 || options.reconnectDelayMs > 60000))
@@ -230,7 +233,8 @@ export class AgentClient {
230
233
  if (snapshot.stopConfirmed && ["succeeded", "failed", "cancelled"].includes(snapshot.state))
231
234
  return;
232
235
  try {
233
- for await (const item of this.events(runId, { signal: options.signal, cursor })) {
236
+ let renewed = false;
237
+ for await (const item of this.events(runId, { signal: options.signal, cursor, onRenewal: () => { renewed = true; } })) {
234
238
  if (item.event.generation !== generation)
235
239
  throw new AgentApiError("event_generation_changed", "A run's durable generation changed.", 409);
236
240
  const next = BigInt(item.event.sequence);
@@ -247,31 +251,246 @@ export class AgentClient {
247
251
  if (snapshot.stopConfirmed && ["succeeded", "failed", "cancelled"].includes(snapshot.state))
248
252
  return;
249
253
  }
250
- if (++retries > max)
251
- throw new AgentApiError("stream_closed", "The provider repeatedly closed its active stream.", 503, true);
254
+ // Older providers may change freshness without advancing the event sequence.
255
+ if (!renewed)
256
+ throw new AgentApiError("stream_closed", "The provider closed its active stream.", 503, true);
257
+ retries = 0;
252
258
  }
253
259
  catch (error) {
254
260
  if (options.signal?.aborted)
255
261
  throw options.signal.reason;
256
- if (error instanceof AgentApiError && error.status !== 410 && error.code !== "event_gap" && !error.retryable && ![429, 503, 504].includes(error.status))
262
+ const reload = error instanceof AgentApiError && (error.status === 410 || error.code === "event_gap" || error.code === "stream_closed");
263
+ if (!reload && error instanceof AgentApiError && !error.retryable && ![429, 503, 504].includes(error.status))
257
264
  throw error;
258
- if (error instanceof AgentApiError && error.code === "stream_closed" || ++retries > max)
265
+ if (++retries > max)
259
266
  throw error;
267
+ if (reload) {
268
+ snapshot = await this.run(runId, options);
269
+ if (snapshot.generation !== generation)
270
+ throw new AgentApiError("event_generation_changed", "A run's durable generation changed.", 409);
271
+ cursor = snapshot.cursor;
272
+ sequence = BigInt(snapshot.lastSequence);
273
+ yield { kind: "snapshot", snapshot };
274
+ }
260
275
  }
261
276
  options.signal?.throwIfAborted();
262
- snapshot = await this.run(runId, options);
263
- if (snapshot.generation !== generation)
264
- throw new AgentApiError("event_generation_changed", "A run's durable generation changed.", 409);
265
- cursor = snapshot.cursor;
266
- sequence = BigInt(snapshot.lastSequence);
267
- generation = snapshot.generation;
268
- yield { kind: "snapshot", snapshot };
269
277
  if (!snapshot.stopConfirmed)
270
278
  await pause(options.reconnectDelayMs ?? 250, options.signal);
271
279
  }
272
280
  options.signal?.throwIfAborted();
273
281
  }
274
282
  }
283
+ async function historyResponse(options, accept, page, endpoint, parameters) {
284
+ const url = new URL(options.url);
285
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || !options.token)
286
+ throw new AgentApiError("authorization_invalid", "Invalid installation history binding.", 401);
287
+ if (endpoint) {
288
+ if (!url.pathname.endsWith("/history/events"))
289
+ throw new AgentApiError("authorization_invalid", "Expected an installation history events URL.", 401);
290
+ url.pathname = url.pathname.slice(0, -"events".length) + endpoint;
291
+ for (const [key, value] of Object.entries(parameters ?? {}))
292
+ if (value !== undefined)
293
+ url.searchParams.set(key, String(value));
294
+ }
295
+ const after = agentReplayCursor(options.cursor);
296
+ if (after)
297
+ url.searchParams.set("after", after);
298
+ if (page?.through)
299
+ url.searchParams.set("through", agentReplayCursor(page.through));
300
+ if (page?.limit !== undefined) {
301
+ if (!Number.isInteger(page.limit) || page.limit < 1 || page.limit > 100)
302
+ throw new AgentApiError("invalid_input", "Page size must be between 1 and 100.", 400);
303
+ url.searchParams.set("limit", String(page.limit));
304
+ }
305
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
306
+ headers: { accept, authorization: `Bearer ${options.token}` },
307
+ signal: options.signal, redirect: "error", cache: "no-store",
308
+ });
309
+ if (!response.ok) {
310
+ const raw = await boundedText(response, MAX_BYTES);
311
+ let detail;
312
+ try {
313
+ detail = JSON.parse(raw)?.error;
314
+ }
315
+ catch { /* Older providers may return a plain 404. */ }
316
+ if (endpoint === "live" && (response.status === 404 || response.status === 422 && ["unsupported_operation", "unsupported_capability"].includes(detail?.code ?? "")))
317
+ throw new AgentApiError("history_live_unsupported", "The provider does not support live history recovery.", 404);
318
+ throw new AgentApiError(detail?.code ?? "provider_failed", detail?.message ?? `History request failed (${response.status}).`, response.status, detail?.retryable === true);
319
+ }
320
+ if (response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== accept) {
321
+ await response.body?.cancel();
322
+ throw new AgentApiError("response_invalid", "The provider returned an unexpected history representation.", 502);
323
+ }
324
+ return response;
325
+ }
326
+ function historyObject(value) {
327
+ return typeof value === "object" && value !== null && !Array.isArray(value);
328
+ }
329
+ const historyIdentity = (id) => typeof id === "string" && id.length > 0 && id.length <= 512;
330
+ const historyPosition = (n) => typeof n === "number" && Number.isSafeInteger(n) && n > 0;
331
+ function historyObservation(value, cursor, provider) {
332
+ if (!historyObject(value) || typeof cursor !== "string" || !agentReplayCursor(cursor))
333
+ throw new AgentApiError("event_invalid", "The history observation is missing its cursor.", 502);
334
+ const { sessionId, runId, generation, userId, principalId } = value;
335
+ if (!historyIdentity(sessionId) || !historyIdentity(runId) || !historyIdentity(generation) || !historyIdentity(userId) || !historyIdentity(principalId) || !historyObject(value.item))
336
+ throw new AgentApiError("event_invalid", "The history observation is missing its identity.", 502);
337
+ const raw = value.item;
338
+ let item;
339
+ let snapshot;
340
+ if (raw.kind === "event") {
341
+ validateAgentEvent(raw.event);
342
+ if (typeof raw.cursor !== "string" || !agentReplayCursor(raw.cursor) || raw.event.runId !== runId || raw.event.generation !== generation)
343
+ throw new AgentApiError("event_invalid", "History event identity changed.", 502);
344
+ if (raw.event.type === "run.updated")
345
+ snapshot = raw.event.data.snapshot;
346
+ item = { kind: "event", event: raw.event, cursor: raw.cursor };
347
+ }
348
+ else if (raw.kind === "snapshot") {
349
+ validateAgentRunSnapshot(raw.snapshot);
350
+ item = { kind: "snapshot", snapshot: raw.snapshot };
351
+ snapshot = raw.snapshot;
352
+ }
353
+ else
354
+ throw new AgentApiError("event_invalid", "Unknown history observation.", 502);
355
+ if (snapshot && (snapshot.ref.id !== runId || snapshot.sessionId !== sessionId || snapshot.generation !== generation
356
+ || provider && !sameProvider(provider, snapshot.ref.provider)))
357
+ throw new AgentApiError("event_invalid", "History snapshot identity changed.", 502);
358
+ const { epoch, sessionPosition } = value;
359
+ if (value.sourceHistoryIncomplete !== undefined && value.sourceHistoryIncomplete !== true || epoch !== undefined && !historyIdentity(epoch) || sessionPosition !== undefined && (!epoch || !historyPosition(sessionPosition)))
360
+ throw new AgentApiError("event_invalid", "Invalid session history position.", 502);
361
+ return { sessionId, runId, generation, userId, principalId, item, cursor,
362
+ ...(epoch !== undefined ? { epoch } : {}), ...(sessionPosition !== undefined ? { sessionPosition } : {}),
363
+ ...(value.sourceHistoryIncomplete ? { sourceHistoryIncomplete: true } : {}) };
364
+ }
365
+ /** Open one read-only installation subscription. Resume from the last durably applied position. */
366
+ export async function* watchAgentHistory(options) {
367
+ const idleMs = options.idleTimeoutMs ?? 60000;
368
+ if (!Number.isSafeInteger(idleMs) || idleMs < 1 || idleMs > 2147483647)
369
+ throw new AgentApiError("invalid_input", "Invalid history heartbeat timeout.", 400);
370
+ const response = await historyResponse(options, "text/event-stream");
371
+ try {
372
+ await options.onOpen?.();
373
+ }
374
+ catch (error) {
375
+ await response.body?.cancel().catch(() => { });
376
+ throw error;
377
+ }
378
+ for await (const frame of parseAgentSse(response, MAX_BYTES + 32768, idleMs)) {
379
+ if (frame.event !== "observation")
380
+ continue;
381
+ let value;
382
+ try {
383
+ value = JSON.parse(frame.data);
384
+ }
385
+ catch {
386
+ throw new AgentApiError("event_invalid", "Invalid installation history JSON.", 502);
387
+ }
388
+ yield historyObservation(value, frame.id, options.provider);
389
+ }
390
+ }
391
+ /** Subscribe at the provider's current boundary. Supply a previous cursor to validate archive ancestry. */
392
+ export async function* watchLiveAgentHistory(options) {
393
+ const idle = options.idleTimeoutMs ?? 60000;
394
+ if (!Number.isSafeInteger(idle) || idle < 1 || idle > 2147483647)
395
+ throw new AgentApiError("invalid_input", "Invalid heartbeat timeout.", 400);
396
+ const response = await historyResponse(options, "text/event-stream", undefined, "live");
397
+ let ready = false;
398
+ try {
399
+ for await (const frame of parseAgentSse(response, MAX_BYTES + 32768, idle)) {
400
+ const value = JSON.parse(frame.data);
401
+ if (!ready) {
402
+ if (frame.event !== "ready" || !historyObject(value) || typeof value.through !== "string" || !agentReplayCursor(value.through))
403
+ throw new AgentApiError("event_invalid", "The provider did not establish a live history boundary.", 502);
404
+ ready = true;
405
+ await options.onOpen?.();
406
+ await options.onReady(value.through);
407
+ }
408
+ else {
409
+ if (frame.event !== "observation")
410
+ throw new AgentApiError("event_invalid", "Unexpected live history frame.", 502);
411
+ const observation = historyObservation(value, frame.id, options.provider);
412
+ const transient = observation.item.kind === "event" && ["message.delta", "tool.output"].includes(observation.item.event.type);
413
+ if (!observation.epoch || transient !== (observation.sessionPosition === undefined))
414
+ throw new AgentApiError("event_invalid", "Invalid live record position.", 502);
415
+ yield observation;
416
+ }
417
+ }
418
+ }
419
+ finally {
420
+ await response.body?.cancel().catch(() => { });
421
+ }
422
+ if (!ready)
423
+ throw new AgentApiError("stream_closed", "The stream closed before its live boundary.", 503, true);
424
+ }
425
+ export async function readAgentHistoryStates(options) {
426
+ const response = await historyResponse({ ...options, cursor: undefined }, "application/json", options, "states", { afterSession: options.afterSession });
427
+ const page = JSON.parse(await boundedText(response, 2 * MAX_BYTES + 32768));
428
+ if (!historyObject(page) || !isHistoryCursor(page.through) || options.through && page.through !== options.through
429
+ || !Array.isArray(page.sessions) || page.sessions.length > (options.limit ?? 100)
430
+ || !(page.nextSession === null || historyIdentity(page.nextSession)))
431
+ throw new AgentApiError("response_invalid", "Invalid provider history state page.", 502);
432
+ const sessions = [];
433
+ let previous = options.afterSession ?? "";
434
+ for (const state of page.sessions) {
435
+ if (!historyObject(state) || !historyIdentity(state.sessionId) || state.sessionId <= previous || !historyIdentity(state.userId)
436
+ || state.sourceHistoryIncomplete !== undefined && state.sourceHistoryIncomplete !== true || !historyIdentity(state.principalId) || !historyIdentity(state.epoch) || !historyPosition(state.head))
437
+ throw new AgentApiError("response_invalid", "Invalid provider session state.", 502);
438
+ validateAgentRunSnapshot(state.snapshot);
439
+ if (state.sessionId !== state.snapshot.sessionId || options.provider && !sameProvider(options.provider, state.snapshot.ref.provider))
440
+ throw new AgentApiError("response_invalid", "Provider session state identity changed.", 502);
441
+ previous = state.sessionId;
442
+ sessions.push({ sessionId: state.sessionId, userId: state.userId, principalId: state.principalId,
443
+ epoch: state.epoch, head: state.head, snapshot: state.snapshot, ...(state.sourceHistoryIncomplete ? { sourceHistoryIncomplete: true } : {}) });
444
+ }
445
+ if (page.nextSession !== null && (!sessions.length || page.nextSession !== previous))
446
+ throw new AgentApiError("response_invalid", "The history states page did not advance.", 502);
447
+ return { through: page.through, sessions, nextSession: page.nextSession };
448
+ }
449
+ function isHistoryCursor(value) {
450
+ return typeof value === "string" && Boolean(agentReplayCursor(value));
451
+ }
452
+ export async function readAgentHistoryRange(options) {
453
+ const { sessionId, epoch, from, to } = options;
454
+ if (!historyIdentity(sessionId) || !historyIdentity(epoch) || !isHistoryCursor(options.through)
455
+ || !historyPosition(from) || !historyPosition(to) || to < from)
456
+ throw new AgentApiError("invalid_input", "Invalid session history range.", 400);
457
+ const response = await historyResponse({ ...options, cursor: undefined }, "application/json", options, "range", { sessionId, epoch, from, to });
458
+ const page = JSON.parse(await boundedText(response, 2 * MAX_BYTES + 32768));
459
+ if (!historyObject(page) || !Array.isArray(page.observations) || !page.observations.length || page.observations.length > (options.limit ?? 100))
460
+ throw new AgentApiError("response_invalid", "Invalid session history range page.", 502);
461
+ const observations = page.observations.map((value, index) => {
462
+ const item = historyObservation(value, value?.cursor, options.provider);
463
+ if (item.sessionId !== sessionId || item.epoch !== epoch || item.sessionPosition !== from + index || item.sessionPosition > to
464
+ || item.item.kind === "event" && ["message.delta", "tool.output"].includes(item.item.event.type))
465
+ throw new AgentApiError("response_invalid", "Invalid durable session record or range ordering.", 502);
466
+ return item;
467
+ });
468
+ const next = from + observations.length;
469
+ const nextPosition = next <= to ? next : null;
470
+ if (page.nextPosition !== nextPosition)
471
+ throw new AgentApiError("response_invalid", "The session range page did not advance.", 502);
472
+ return { observations, nextPosition };
473
+ }
474
+ /** Read a bounded page at a stable installation feed position. Pass through to subsequent pages. */
475
+ export async function readAgentHistoryPage(options) {
476
+ const response = await historyResponse(options, "application/json", options);
477
+ const raw = await boundedText(response, 2 * MAX_BYTES + 32768);
478
+ let page;
479
+ try {
480
+ page = JSON.parse(raw);
481
+ }
482
+ catch {
483
+ throw new AgentApiError("response_invalid", "Invalid installation history page JSON.", 502);
484
+ }
485
+ if (!historyObject(page) || typeof page.through !== "string" || !agentReplayCursor(page.through)
486
+ || options.through && page.through !== options.through || !Array.isArray(page.observations) || page.observations.length > (options.limit ?? 100)
487
+ || !(page.nextCursor === null || typeof page.nextCursor === "string" && agentReplayCursor(page.nextCursor)))
488
+ throw new AgentApiError("response_invalid", "Invalid installation history page.", 502);
489
+ const observations = page.observations.map(value => historyObservation(value, value?.cursor, options.provider));
490
+ if (page.nextCursor !== null && (!observations.length || page.nextCursor !== observations.at(-1)?.cursor || page.nextCursor === options.cursor))
491
+ throw new AgentApiError("response_invalid", "The history page did not advance.", 502);
492
+ return { observations, through: page.through, nextCursor: page.nextCursor };
493
+ }
275
494
  function queryString(value) {
276
495
  const query = new URLSearchParams();
277
496
  for (const [key, item] of Object.entries(value))
@@ -302,8 +521,21 @@ async function boundedText(response, max) {
302
521
  }
303
522
  return Buffer.concat(chunks).toString("utf8");
304
523
  }
524
+ async function readSseChunk(reader, idleMs) {
525
+ if (idleMs === undefined)
526
+ return reader.read();
527
+ let timer;
528
+ try {
529
+ return await Promise.race([reader.read(), new Promise((_, reject) => {
530
+ timer = setTimeout(() => reject(new AgentApiError("history_stream_idle", "Provider history heartbeats stopped.", 504, true)), idleMs);
531
+ })]);
532
+ }
533
+ finally {
534
+ clearTimeout(timer);
535
+ }
536
+ }
305
537
  /** Streaming decoder handles split UTF-8, CR/LF framing, multi-line data and comment heartbeats. */
306
- export async function* parseAgentSse(response, maxBytes = MAX_BYTES) {
538
+ export async function* parseAgentSse(response, maxBytes = MAX_BYTES, idleMs) {
307
539
  const reader = response.body?.getReader();
308
540
  if (!reader)
309
541
  throw new AgentApiError("event_invalid", "The event stream is empty.", 502);
@@ -311,7 +543,7 @@ export async function* parseAgentSse(response, maxBytes = MAX_BYTES) {
311
543
  let buffer = "", id = "", event = "message", data = [], bytes = 0;
312
544
  try {
313
545
  while (true) {
314
- const chunk = await reader.read();
546
+ const chunk = await readSseChunk(reader, idleMs);
315
547
  buffer += decoder.decode(chunk.value, { stream: !chunk.done });
316
548
  let match;
317
549
  while ((match = /\r\n|\r|\n/.exec(buffer))) {
@@ -16,6 +16,11 @@ const refProperties = { appId: text(), installationId: text(), key: text() };
16
16
  const baseControl = { requestId: uuid, expectedGeneration: uuid, expectedRevision: revision };
17
17
  const terminalStates = ["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"];
18
18
  const phases = ["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"];
19
+ const historyObservation = {
20
+ sessionId: id, runId: id, generation: uuid, principalId: text(512), userId: text(512),
21
+ item: { oneOf: [object({ kind: { const: "snapshot" }, snapshot: ref("RunSnapshot") }),
22
+ object({ kind: { const: "event" }, event: ref("Event"), cursor: text(8192) })] },
23
+ };
19
24
  export const AGENT_SCHEMAS = {
20
25
  ProviderRef: object(refProperties),
21
26
  QualifiedRef: object({ provider: ref("ProviderRef"), id }),
@@ -71,6 +76,16 @@ export const AGENT_SCHEMAS = {
71
76
  description: "Latest root context.updated observation within the snapshot watermark; its canonical positive sequence is at most lastSequence. Null usage explicitly clears the observation. Absence means no retained observation. Payloads share the bounded snapshot/event JSON byte allowance." },
72
77
  decisions: list(object({ decision: ref("PendingDecision"), state: { enum: ["pending", "resolved", "superseded", "unknown"] }, response: ref("DecisionResponse") }, ["decision", "state"]), 256),
73
78
  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),
79
+ HistoryObservation: object(historyObservation),
80
+ LiveHistoryReady: object({ through: text(8192) }),
81
+ LiveHistoryObservation: object({ ...historyObservation, epoch: uuid, sessionPosition: positive, sourceHistoryIncomplete: { const: true } }, [...Object.keys(historyObservation), "epoch"]),
82
+ HistoryStates: object({ through: text(8192), nextSession: nullableText, sessions: list(object({
83
+ sessionId: id, userId: text(512), principalId: text(512), epoch: uuid, head: positive, snapshot: ref("RunSnapshot"), sourceHistoryIncomplete: { const: true },
84
+ }, ["sessionId", "userId", "principalId", "epoch", "head", "snapshot"]), 100) }),
85
+ HistoryRange: object({ nextPosition: { type: ["integer", "null"], minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
86
+ observations: list(object({ ...historyObservation, cursor: text(8192), epoch: uuid, sessionPosition: positive, sourceHistoryIncomplete: { const: true } }, [...Object.keys(historyObservation), "cursor", "epoch", "sessionPosition"]), 100) }),
87
+ HistoryPage: object({ observations: list(object({ ...historyObservation, cursor: text(8192) }), 100),
88
+ through: text(8192), nextCursor: { type: ["string", "null"] } }),
74
89
  Session: object({ ref: ref("QualifiedRef"), revision, configurationRevision: revision, configurationDigest: digest,
75
90
  nativeState: { enum: ["not_created", "available", "missing", "unavailable", "unknown"] }, activeRun: { oneOf: [ref("QualifiedRef"), { type: "null" }] },
76
91
  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),
@@ -106,9 +121,30 @@ function operation(operationId, response, input, pathParameters = [], statuses =
106
121
  return { operationId, security: [{ coreOperation: [] }], parameters: pathParameters.map(parameter), ...(input ? { requestBody: { required: true, content: { "application/json": { schema: ref(input) } } } } : {}),
107
122
  responses: { ...errors, ...Object.fromEntries(statuses.map(status => [String(status), { description: "Authorized durable result.", headers: { "Cache-Control": { schema: { const: "no-store" } } }, content: { "application/json": { schema: ref(response) } } }])) } };
108
123
  }
124
+ const historySecurity = [{ installationHistory: [] }];
125
+ const historyParam = (name, schema, required = false) => ({ name, in: "query", schema, required });
126
+ const pageLimit = historyParam("limit", { type: "integer", minimum: 1, maximum: 100 });
109
127
  export const AGENT_OPENAPI = {
110
128
  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." },
111
129
  paths: {
130
+ "/history/live": { get: { operationId: "history.live", security: historySecurity, parameters: [historyParam("after", text(8192))],
131
+ 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.",
132
+ responses: { ...errors, "200": { description: "Ready boundary followed by live observations.", content: {
133
+ "text/event-stream": { schema: { type: "string" }, "x-event-schemas": { ready: ref("LiveHistoryReady"), observation: ref("LiveHistoryObservation") } },
134
+ } } } } },
135
+ "/history/states": { get: { operationId: "history.states", security: historySecurity,
136
+ parameters: [historyParam("through", text(8192)), historyParam("afterSession", id), pageLimit],
137
+ 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.",
138
+ responses: { ...errors, "200": { description: "States for the calling installation.", content: { "application/json": { schema: ref("HistoryStates") } } } } } },
139
+ "/history/range": { get: { operationId: "history.range", security: historySecurity,
140
+ parameters: [historyParam("through", text(8192), true), historyParam("sessionId", id, true), historyParam("epoch", uuid, true),
141
+ historyParam("from", positive, true), historyParam("to", positive, true), pageLimit],
142
+ description: "Read an inclusive interval of durable positions for one session and history epoch. nextPosition is the first unread position in the requested interval.",
143
+ responses: { ...errors, "200": { description: "Ordered durable session records.", content: { "application/json": { schema: ref("HistoryRange") } } } } } },
144
+ "/history/events": { get: { operationId: "history.events", security: [{ installationHistory: [] }],
145
+ parameters: [{ name: "after", in: "query", schema: text(8192) }, { name: "through", in: "query", schema: text(8192) }, { name: "limit", in: "query", schema: { type: "integer", minimum: 1, maximum: 100 } }],
146
+ description: "Resumable, read-only installation history. Frames use event: observation with an opaque installation feed position in id. Commit each observation before saving this position.",
147
+ responses: { ...errors, "200": { description: "History for the authenticated consumer installation.", content: { "text/event-stream": { schema: { type: "string" }, "x-event-schema": ref("HistoryObservation") }, "application/json": { schema: ref("HistoryPage") } } } } } },
112
148
  "/capabilities": { get: operation("capabilities", "Capabilities") },
113
149
  "/connections": { get: operation("connections.list", "ConnectionPage") },
114
150
  "/connections/{connectionId}/models": { get: operation("connections.models", "ModelCatalog", undefined, ["connectionId"]) },
@@ -126,7 +162,7 @@ export const AGENT_OPENAPI = {
126
162
  "/runs/{runId}/cancel": { post: operation("runs.cancel", "ControlReceipt", "CancelInput", ["runId"], [200, 202]) },
127
163
  "/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." } },
128
164
  "/runs/{runId}/controls/{requestId}": { get: operation("runs.controls.read", "ControlReceipt", undefined, ["runId", "requestId"]) },
129
- }, components: { securitySchemes: { coreOperation: { type: "http", scheme: "bearer", description: "Fresh Core exact-operation credential, never the caller's service/user token." } }, schemas: AGENT_SCHEMAS },
165
+ }, 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 },
130
166
  };
131
167
  function localRefs(value) {
132
168
  if (Array.isArray(value))
package/dist/agent.d.ts CHANGED
@@ -6,6 +6,8 @@ export type AgentRunRef = RunRef;
6
6
  export declare const AGENT_API_VERSION: 1;
7
7
  export declare const AGENT_EVENT_VERSION: "agent-event.1";
8
8
  export declare const AGENT_CAPABILITIES: {
9
+ readonly installationHistory: "installation-history";
10
+ readonly liveInstallationHistory: "installation-history.live";
9
11
  readonly resume: "session.resume";
10
12
  readonly configuration: "configuration.resume-compatible";
11
13
  readonly images: "input.images";
@@ -452,6 +454,28 @@ export type AgentWatchItem = {
452
454
  event: AgentEvent;
453
455
  cursor: string;
454
456
  };
457
+ /** One installation feed receipt. Its cursor is independent of the per-run replay position. */
458
+ export type AgentHistoryObservation = {
459
+ sessionId: string;
460
+ runId: string;
461
+ generation: string;
462
+ userId: string;
463
+ principalId: string;
464
+ item: AgentWatchItem;
465
+ cursor: string;
466
+ epoch?: string;
467
+ sessionPosition?: number;
468
+ sourceHistoryIncomplete?: true;
469
+ };
470
+ export type AgentHistorySessionState = {
471
+ sessionId: string;
472
+ userId: string;
473
+ principalId: string;
474
+ epoch: string;
475
+ head: number;
476
+ snapshot: AgentRunSnapshot;
477
+ sourceHistoryIncomplete?: true;
478
+ };
455
479
  export type AgentErrorDetail = {
456
480
  code: string;
457
481
  message: string;
@@ -499,6 +523,12 @@ export type AgentAuthorizationRequest = {
499
523
  sessionId?: string;
500
524
  runId?: string;
501
525
  configurationDigest?: string;
526
+ /** Originating chat on runs.start. The consumer supplies its own app-relative viewer route. */
527
+ conversation?: {
528
+ sessionId: string;
529
+ viewerPath: string;
530
+ title: string;
531
+ };
502
532
  ceiling?: {
503
533
  mcp?: AgentMcpSelection;
504
534
  resources?: AgentResource[];
package/dist/agent.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export const AGENT_API_VERSION = 1;
2
2
  export const AGENT_EVENT_VERSION = "agent-event.1";
3
3
  export const AGENT_CAPABILITIES = {
4
+ installationHistory: "installation-history",
5
+ liveInstallationHistory: "installation-history.live",
4
6
  resume: "session.resume", configuration: "configuration.resume-compatible", images: "input.images",
5
7
  noNativeTools: "native-tools.none", skills: "skills.catalog", exclusiveSkills: "skills.exclusive-selection",
6
8
  coreMcp: "mcp.core", externalMcp: "mcp.external", modelChange: "model.change-on-resume",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hosty-sdk/app",
3
- "version": "0.48.0",
3
+ "version": "0.50.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",