stitchkit 0.68.11 → 0.70.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.
Files changed (125) hide show
  1. package/README.md +30 -1
  2. package/dist/agent-runtime/coding-tool-contract.d.ts +156 -0
  3. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -0
  4. package/dist/agent-runtime/coding-tool-files.d.ts +3 -0
  5. package/dist/agent-runtime/coding-tool-files.d.ts.map +1 -0
  6. package/dist/agent-runtime/coding-tool-paths.d.ts +20 -0
  7. package/dist/agent-runtime/coding-tool-paths.d.ts.map +1 -0
  8. package/dist/agent-runtime/coding-tool-search-patch.d.ts +3 -0
  9. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -0
  10. package/dist/agent-runtime/coding-tool-shell.d.ts +3 -0
  11. package/dist/agent-runtime/coding-tool-shell.d.ts.map +1 -0
  12. package/dist/agent-runtime/coding-tools.d.ts +17 -0
  13. package/dist/agent-runtime/coding-tools.d.ts.map +1 -0
  14. package/dist/agent-runtime/compaction.d.ts +2 -0
  15. package/dist/agent-runtime/compaction.d.ts.map +1 -1
  16. package/dist/agent-runtime/contained-files.d.ts +56 -0
  17. package/dist/agent-runtime/contained-files.d.ts.map +1 -0
  18. package/dist/agent-runtime/control-schema.d.ts +1074 -0
  19. package/dist/agent-runtime/control-schema.d.ts.map +1 -0
  20. package/dist/agent-runtime/conversations.d.ts +128 -0
  21. package/dist/agent-runtime/conversations.d.ts.map +1 -0
  22. package/dist/agent-runtime/event-schema.d.ts +96 -0
  23. package/dist/agent-runtime/event-schema.d.ts.map +1 -1
  24. package/dist/agent-runtime/harness-contract.d.ts +169 -0
  25. package/dist/agent-runtime/harness-contract.d.ts.map +1 -0
  26. package/dist/agent-runtime/harness-control.d.ts +25 -0
  27. package/dist/agent-runtime/harness-control.d.ts.map +1 -0
  28. package/dist/agent-runtime/harness-file-resources.d.ts +33 -0
  29. package/dist/agent-runtime/harness-file-resources.d.ts.map +1 -0
  30. package/dist/agent-runtime/harness-resources.d.ts +5 -0
  31. package/dist/agent-runtime/harness-resources.d.ts.map +1 -0
  32. package/dist/agent-runtime/harness.d.ts +12 -0
  33. package/dist/agent-runtime/harness.d.ts.map +1 -0
  34. package/dist/agent-runtime/history.d.ts +2 -0
  35. package/dist/agent-runtime/history.d.ts.map +1 -1
  36. package/dist/agent-runtime/models.d.ts +199 -0
  37. package/dist/agent-runtime/models.d.ts.map +1 -1
  38. package/dist/agent-runtime/prompt.d.ts +2 -0
  39. package/dist/agent-runtime/prompt.d.ts.map +1 -1
  40. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  41. package/dist/agent-runtime/runtime.d.ts +11 -3
  42. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  43. package/dist/agent-runtime/schemas.d.ts +49 -0
  44. package/dist/agent-runtime/schemas.d.ts.map +1 -1
  45. package/dist/agent-runtime/sqlite.d.ts +2 -0
  46. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  47. package/dist/agent-runtime/store-driver.d.ts +61 -212
  48. package/dist/agent-runtime/store-driver.d.ts.map +1 -1
  49. package/dist/agent-runtime/store.d.ts +368 -1
  50. package/dist/agent-runtime/store.d.ts.map +1 -1
  51. package/dist/agent-runtime/terminal-commit.d.ts +12 -1
  52. package/dist/agent-runtime/terminal-commit.d.ts.map +1 -1
  53. package/dist/agent-runtime/terminal-status.d.ts +8 -0
  54. package/dist/agent-runtime/terminal-status.d.ts.map +1 -1
  55. package/dist/agent-runtime-browser.d.ts +1 -0
  56. package/dist/agent-runtime-browser.d.ts.map +1 -1
  57. package/dist/agent-runtime-browser.js +217 -1
  58. package/dist/agent-runtime-coding-tools.d.ts +2 -0
  59. package/dist/agent-runtime-coding-tools.d.ts.map +1 -0
  60. package/dist/agent-runtime-coding-tools.js +766 -0
  61. package/dist/agent-runtime-harness.d.ts +2 -0
  62. package/dist/agent-runtime-harness.d.ts.map +1 -0
  63. package/dist/agent-runtime-harness.js +704 -0
  64. package/dist/agent-runtime-openrouter.d.ts +14 -1
  65. package/dist/agent-runtime-openrouter.d.ts.map +1 -1
  66. package/dist/agent-runtime-openrouter.js +211 -0
  67. package/dist/agent-runtime-sqlite-bun.js +4 -3
  68. package/dist/agent-runtime-sqlite-node.js +4 -3
  69. package/dist/agent-runtime.d.ts +5 -3
  70. package/dist/agent-runtime.d.ts.map +1 -1
  71. package/dist/agent-runtime.js +108 -2580
  72. package/dist/application/diagnostic-journal-contract.d.ts +164 -0
  73. package/dist/application/diagnostic-journal-contract.d.ts.map +1 -0
  74. package/dist/application/diagnostic-journal-manager.d.ts +12 -0
  75. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -0
  76. package/dist/application/diagnostic-journal-storage.d.ts +29 -0
  77. package/dist/application/diagnostic-journal-storage.d.ts.map +1 -0
  78. package/dist/application/diagnostic-journal.d.ts +11 -0
  79. package/dist/application/diagnostic-journal.d.ts.map +1 -0
  80. package/dist/application.d.ts +2 -0
  81. package/dist/application.d.ts.map +1 -1
  82. package/dist/application.js +561 -17
  83. package/dist/browser/socket-io.d.ts.map +1 -1
  84. package/dist/cli.js +9 -6
  85. package/dist/{index-t23p2b68.js → index-0yphgata.js} +1 -1
  86. package/dist/{index-8vpzxg55.js → index-10gbbbaa.js} +103 -2
  87. package/dist/{index-hcx9yypn.js → index-38hs3a58.js} +13 -11
  88. package/dist/index-3xnq72rz.js +21 -0
  89. package/dist/index-7rey2b8s.js +73 -0
  90. package/dist/{index-22tjt2rk.js → index-aczggrty.js} +1 -1
  91. package/dist/index-bd17ytae.js +192 -0
  92. package/dist/{index-xyvxez9r.js → index-da1aqnhb.js} +5 -5
  93. package/dist/index-es0h4w26.js +63 -0
  94. package/dist/{index-hqza5nde.js → index-hsabxjz0.js} +78 -77
  95. package/dist/{index-f24xg2cw.js → index-ktsps64f.js} +4 -2
  96. package/dist/{index-2t6zt5cg.js → index-mjx0wt4c.js} +11 -7
  97. package/dist/{index-y2ctppmg.js → index-qzbg46b6.js} +10 -74
  98. package/dist/{index-bt5179zb.js → index-s8nt8c22.js} +16 -11
  99. package/dist/index-tg3m2ec5.js +157 -0
  100. package/dist/{index-hxh98zbm.js → index-vbf2p6me.js} +1 -1
  101. package/dist/index-vc498pst.js +51 -0
  102. package/dist/{index-pgsyp3xh.js → index-vj3vvpaa.js} +1 -192
  103. package/dist/index-vy5bjy07.js +2569 -0
  104. package/dist/{index-hb0mncmj.js → index-wc80at9n.js} +2 -2
  105. package/dist/{index-eqqyd9v8.js → index-wwst0td5.js} +2 -46
  106. package/dist/{index-ysphyxax.js → index-x1th9s8c.js} +23 -2
  107. package/dist/index-xbtcszs7.js +202 -0
  108. package/dist/{index-grgvpbch.js → index-y3w12g8d.js} +4 -2
  109. package/dist/index.js +51 -37
  110. package/dist/internal/ai-sdk-typed.d.ts +14 -0
  111. package/dist/internal/ai-sdk-typed.d.ts.map +1 -0
  112. package/dist/node.js +6 -5
  113. package/dist/observability/index.js +5 -4
  114. package/dist/realtime/request.d.ts +5 -0
  115. package/dist/realtime/request.d.ts.map +1 -1
  116. package/dist/remote.js +7 -6
  117. package/dist/server/index.js +13 -11
  118. package/dist/testing.js +6 -5
  119. package/dist/tool-invoker.js +7 -5
  120. package/dist/tools/agent-tool-error.d.ts +14 -0
  121. package/dist/tools/agent-tool-error.d.ts.map +1 -0
  122. package/dist/tools/agent.d.ts.map +1 -1
  123. package/dist/tools.js +24 -17
  124. package/llms-full.txt +386 -29
  125. package/package.json +10 -2
@@ -1,16 +1,18 @@
1
1
  import {
2
2
  AgentAdmissionReceiptSchema,
3
+ AgentConversationMessagePageSchema,
4
+ AgentConversationPageSchema,
3
5
  AgentHistoryMutationSchema,
4
6
  AgentRecoverableDescriptorSchema,
5
7
  AgentRecoverablePageSchema,
6
8
  AgentRuntimeHeadSchema,
7
9
  AgentStoredRunSchema,
8
10
  createAgentRuntimeStore
9
- } from "./index-hqza5nde.js";
11
+ } from "./index-hsabxjz0.js";
10
12
  import {
11
13
  AgentMessageSchema,
12
14
  AgentRunSchema
13
- } from "./index-ysphyxax.js";
15
+ } from "./index-x1th9s8c.js";
14
16
 
15
17
  // src/agent-runtime/sqlite.ts
16
18
  import { z } from "zod";
@@ -35,6 +37,15 @@ var RecoverableRowSchema = z.object({
35
37
  });
36
38
  var MetaRowSchema = z.object({ value: z.string() });
37
39
  var TableRowSchema = z.object({ name: z.string() });
40
+ var ConversationHeadRowSchema = z.object({
41
+ conversation_id: z.string(),
42
+ version: z.number().int().nonnegative()
43
+ });
44
+ var CountRowSchema = z.object({ count: z.number().int().nonnegative() });
45
+ var MessagePageRowSchema = z.object({
46
+ position: z.number().int().nonnegative(),
47
+ payload: z.string()
48
+ });
38
49
  var SCHEMA_VERSION = 1;
39
50
  var TABLES = [
40
51
  "stitchkit_agent_runtime_heads",
@@ -70,6 +81,22 @@ function recoveryCursor(conversationId, runId) {
70
81
  function parseRecoveryCursor(cursor) {
71
82
  return z.tuple([z.string().min(1), z.string().min(1)]).parse(parseJson(cursor));
72
83
  }
84
+ function conversationCursor(conversationId) {
85
+ return encodeJson([conversationId]);
86
+ }
87
+ function parseConversationCursor(cursor) {
88
+ return z.tuple([z.string().min(1)]).parse(parseJson(cursor))[0];
89
+ }
90
+ function messageCursor(position) {
91
+ return encodeJson([position]);
92
+ }
93
+ function parseMessageCursor(cursor) {
94
+ return z.tuple([z.int().nonnegative()]).parse(parseJson(cursor))[0];
95
+ }
96
+ function messagePreview(message) {
97
+ const text = message.parts.find((part) => part.type === "text");
98
+ return text?.type === "text" ? text.text.slice(0, 160) : message.role;
99
+ }
73
100
  function initializeAgentRuntimeSqlite(database) {
74
101
  const existing = database.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'stitchkit_agent_runtime_%' ORDER BY name`).all().map((row) => TableRowSchema.parse(row).name);
75
102
  const hasMeta = existing.includes("stitchkit_agent_runtime_meta");
@@ -389,6 +416,80 @@ function createSqliteAgentRuntimeStore(config) {
389
416
  };
390
417
  return {
391
418
  store: createAgentRuntimeStore(driver),
419
+ conversations: {
420
+ list: (input) => serial(async () => {
421
+ if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 1000) {
422
+ throw new TypeError("Conversation page limit must be between 1 and 1000");
423
+ }
424
+ const cursor = input.cursor ? parseConversationCursor(input.cursor) : undefined;
425
+ const search = input.search?.trim();
426
+ const clauses = [
427
+ ...cursor ? ["conversation_id > ?"] : [],
428
+ ...search ? ["instr(conversation_id, ?) > 0"] : []
429
+ ];
430
+ const parameters = [
431
+ ...cursor ? [cursor] : [],
432
+ ...search ? [search] : [],
433
+ input.limit + 1
434
+ ];
435
+ const rows = database.prepare(`
436
+ SELECT conversation_id, version FROM stitchkit_agent_runtime_heads
437
+ ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
438
+ ORDER BY conversation_id ASC LIMIT ?
439
+ `).all(...parameters).map((row) => ConversationHeadRowSchema.parse(row));
440
+ const hasMore = rows.length > input.limit;
441
+ const pageRows = rows.slice(0, input.limit);
442
+ const items = pageRows.map((row) => {
443
+ const latestRaw = database.prepare(`
444
+ SELECT position, payload FROM stitchkit_agent_runtime_messages
445
+ WHERE conversation_id = ? AND active = 1
446
+ ORDER BY position DESC LIMIT 1
447
+ `).get(row.conversation_id);
448
+ if (missing(latestRaw)) {
449
+ throw new Error("Agent conversation head has no active history");
450
+ }
451
+ const latest = AgentMessageSchema.parse(parseJson(MessagePageRowSchema.parse(latestRaw).payload));
452
+ const active = CountRowSchema.parse(database.prepare(`
453
+ SELECT count(*) AS count FROM stitchkit_agent_runtime_runs
454
+ WHERE conversation_id = ?
455
+ AND state IN ('queued', 'running', 'interrupt_requested')
456
+ `).get(row.conversation_id));
457
+ return {
458
+ conversationId: row.conversation_id,
459
+ version: row.version,
460
+ updatedAt: latest.updatedAt,
461
+ preview: messagePreview(latest),
462
+ activeRuns: active.count
463
+ };
464
+ });
465
+ const last = pageRows.at(-1);
466
+ return AgentConversationPageSchema.parse({
467
+ items,
468
+ ...hasMore && last ? { nextCursor: conversationCursor(last.conversation_id) } : {}
469
+ });
470
+ }),
471
+ messages: (input) => serial(async () => {
472
+ if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 1000) {
473
+ throw new TypeError("Conversation message page limit must be between 1 and 1000");
474
+ }
475
+ const cursor = input.cursor ? parseMessageCursor(input.cursor) : undefined;
476
+ const before = input.direction === "before";
477
+ const rows = database.prepare(`
478
+ SELECT position, payload FROM stitchkit_agent_runtime_messages
479
+ WHERE conversation_id = ? AND active = 1
480
+ ${cursor === undefined ? "" : before ? "AND position < ?" : "AND position > ?"}
481
+ ORDER BY position ${before ? "DESC" : "ASC"} LIMIT ?
482
+ `).all(input.conversationId, ...cursor === undefined ? [] : [cursor], input.limit + 1).map((row) => MessagePageRowSchema.parse(row));
483
+ const hasMore = rows.length > input.limit;
484
+ const pageRows = rows.slice(0, input.limit);
485
+ const ordered = before ? [...pageRows].reverse() : pageRows;
486
+ const boundary = pageRows.at(-1);
487
+ return AgentConversationMessagePageSchema.parse({
488
+ items: ordered.map((row) => AgentMessageSchema.parse(parseJson(row.payload))),
489
+ ...hasMore && boundary ? { nextCursor: messageCursor(boundary.position) } : {}
490
+ });
491
+ })
492
+ },
392
493
  async close() {
393
494
  if (closed)
394
495
  return;
@@ -7,7 +7,7 @@ import {
7
7
  defaultSignalSource,
8
8
  guardSignalCallback,
9
9
  reportSignalError
10
- } from "./index-hxh98zbm.js";
10
+ } from "./index-vbf2p6me.js";
11
11
  import {
12
12
  extractIp,
13
13
  getClientInfo,
@@ -18,31 +18,33 @@ import {
18
18
  runWithRequestContext,
19
19
  setRequestEndpoint,
20
20
  setRequestError
21
- } from "./index-f24xg2cw.js";
21
+ } from "./index-ktsps64f.js";
22
22
  import {
23
23
  ShutdownOptionsSchema
24
24
  } from "./index-dk6e56g0.js";
25
25
  import {
26
- DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
27
26
  errorCode,
28
- isUnsafeKey,
29
- joinRoutePath,
30
27
  normalizeError,
31
- parseTrailingWildcard,
32
28
  recordedErrorMessage,
33
29
  resolveTraceContext,
34
- safeJsonParse,
35
30
  validateDeclaredOutput,
36
31
  zodIssues
37
- } from "./index-pgsyp3xh.js";
32
+ } from "./index-bd17ytae.js";
38
33
  import {
39
- isRecord,
40
- transportResult
41
- } from "./index-qyrqwr4c.js";
34
+ DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
35
+ isUnsafeKey,
36
+ joinRoutePath,
37
+ parseTrailingWildcard,
38
+ safeJsonParse
39
+ } from "./index-vj3vvpaa.js";
42
40
  import {
43
41
  AppError,
44
42
  badRequest
45
43
  } from "./index-0w9abg87.js";
44
+ import {
45
+ isRecord,
46
+ transportResult
47
+ } from "./index-qyrqwr4c.js";
46
48
 
47
49
  // src/server/multipart.ts
48
50
  var DEFAULT_MAX_REQUEST_BYTES = 25 * 1024 * 1024;
@@ -0,0 +1,21 @@
1
+ // src/tools/agent-tool-error.ts
2
+ var AGENT_TOOL_ERROR_BRAND = Symbol.for("stitchkit.AgentToolError");
3
+
4
+ class AgentToolError extends Error {
5
+ output;
6
+ constructor(output, cause) {
7
+ let message = "Tool execution failed";
8
+ try {
9
+ message = JSON.stringify(output);
10
+ } catch {}
11
+ super(message, cause === undefined ? undefined : { cause });
12
+ this.name = "AgentToolError";
13
+ this.output = output;
14
+ Object.defineProperty(this, AGENT_TOOL_ERROR_BRAND, { value: true });
15
+ }
16
+ }
17
+ function isAgentToolError(value) {
18
+ return typeof value === "object" && value !== null && AGENT_TOOL_ERROR_BRAND in value;
19
+ }
20
+
21
+ export { AgentToolError, isAgentToolError };
@@ -0,0 +1,73 @@
1
+ import {
2
+ executeToolMethod
3
+ } from "./index-qzbg46b6.js";
4
+ import {
5
+ assertToolExtensionCompatible,
6
+ mergeSchemas,
7
+ projectToolSurface,
8
+ rebuildObject
9
+ } from "./index-22by16v6.js";
10
+
11
+ // src/tools/mount.ts
12
+ import { z } from "zod";
13
+ function applyExtend(base, extra) {
14
+ if (base instanceof z.ZodObject) {
15
+ assertToolExtensionCompatible(base, extra);
16
+ return rebuildObject(base, { ...extra, ...base.shape });
17
+ }
18
+ return z.intersection(z.object(extra), base);
19
+ }
20
+ function contractToolMountable(projected, extend) {
21
+ const method = projected.source;
22
+ const baseArgumentSchema = mergeSchemas(method.paramsSchema, method.inputSchema);
23
+ const argumentSchema = projected.shouldExtend && extend ? applyExtend(baseArgumentSchema, extend.schema) : baseArgumentSchema;
24
+ return {
25
+ method,
26
+ name: projected.name,
27
+ argumentSchema,
28
+ presentationSchema: projected.presentationSchema,
29
+ shouldExtend: projected.shouldExtend
30
+ };
31
+ }
32
+ function collectTools(service, transport, config = {}) {
33
+ const { extend, flattenUnionInput = false, assertNames = true } = config;
34
+ const tools = [];
35
+ for (const projected of projectToolSurface({ services: [service] }, transport === "HTTP" ? "AGENT" : transport, {
36
+ extend,
37
+ flattenUnionInput,
38
+ assertNames,
39
+ assertUniqueNames: false
40
+ })) {
41
+ if (projected.kind !== "contract")
42
+ continue;
43
+ tools.push(contractToolMountable(projected, extend));
44
+ }
45
+ return tools;
46
+ }
47
+ function createToolRunner(config) {
48
+ const extension = config.extend ? {
49
+ schema: z.object(config.extend.schema),
50
+ resolve: config.extend.resolve
51
+ } : undefined;
52
+ return async function runOneToolCall(tool, rawArgs, context) {
53
+ return executeToolMethod(tool.method, tool.name, rawArgs, { ...config.context, ...context, source: config.source }, config.hooks, config.lifecycle, config.coerceJsonArgs ?? true, config.onOutputStrip ? (paths) => config.onOutputStrip?.(tool.name, paths) : undefined, tool.shouldExtend ? extension : undefined);
54
+ };
55
+ }
56
+ function formatToolError(result, toolName, errorHint) {
57
+ const err = { error: result.code };
58
+ if (result.details)
59
+ err.details = result.details;
60
+ const hints = [];
61
+ if (result.hint)
62
+ hints.push(result.hint);
63
+ if (errorHint && toolName) {
64
+ const global = errorHint(toolName, result.code);
65
+ if (global)
66
+ hints.push(global);
67
+ }
68
+ if (hints.length > 0)
69
+ err._hint = hints.join(" ");
70
+ return err;
71
+ }
72
+
73
+ export { contractToolMountable, collectTools, createToolRunner, formatToolError };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isUnsafeKey
3
- } from "./index-pgsyp3xh.js";
3
+ } from "./index-vj3vvpaa.js";
4
4
  import {
5
5
  isRecord
6
6
  } from "./index-qyrqwr4c.js";
@@ -0,0 +1,192 @@
1
+ import {
2
+ AppError
3
+ } from "./index-0w9abg87.js";
4
+ import {
5
+ isRecord
6
+ } from "./index-qyrqwr4c.js";
7
+
8
+ // src/internal/errors.ts
9
+ import { z } from "zod";
10
+ function issuePath(path) {
11
+ return path.length > 0 ? path.map(String).join(".") : "(root)";
12
+ }
13
+ function formatZodError(error) {
14
+ const issues = error.issues.slice(0, 5);
15
+ const lines = issues.map((issue) => `${issuePath(issue.path)}: ${issue.message}`);
16
+ const suffix = error.issues.length > 5 ? `
17
+ ...and ${error.issues.length - 5} more issues` : "";
18
+ return lines.join(`
19
+ `) + suffix;
20
+ }
21
+ function zodIssues(error) {
22
+ return error.issues.map((issue) => ({
23
+ path: issuePath(issue.path),
24
+ code: issue.code,
25
+ message: issue.message
26
+ }));
27
+ }
28
+ var MAX_DETAIL_ISSUES = 20;
29
+ function errorCode(err) {
30
+ if (AppError.is(err))
31
+ return err.code;
32
+ if (err instanceof z.ZodError)
33
+ return "VALIDATION_ERROR";
34
+ return;
35
+ }
36
+ function recordedErrorMessage(code, envelopeMessage, thrown) {
37
+ if ((code === "INTERNAL_SERVER_ERROR" || code === "REALTIME_CONTRACT_VIOLATION") && thrown !== undefined) {
38
+ if (thrown instanceof Error)
39
+ return thrown.message;
40
+ if (typeof thrown === "string")
41
+ return thrown;
42
+ }
43
+ return envelopeMessage;
44
+ }
45
+ function normalizeError(err) {
46
+ if (AppError.is(err)) {
47
+ if (err.code === "REALTIME_CONTRACT_VIOLATION") {
48
+ return new AppError("REALTIME_CONTRACT_VIOLATION", "Realtime contract violation", 500);
49
+ }
50
+ return err;
51
+ }
52
+ if (err instanceof z.ZodError) {
53
+ return new AppError("VALIDATION_ERROR", formatZodError(err), 400, {
54
+ issues: zodIssues(err).slice(0, MAX_DETAIL_ISSUES)
55
+ });
56
+ }
57
+ console.error("[stitchkit] unhandled error:", err);
58
+ return new AppError("INTERNAL_SERVER_ERROR", "Internal server error", 500);
59
+ }
60
+ function strippedPaths(before, after, prefix) {
61
+ if (Array.isArray(before)) {
62
+ if (!Array.isArray(after))
63
+ return [];
64
+ return before.flatMap((item, i) => strippedPaths(item, after[i], `${prefix}[${i}]`));
65
+ }
66
+ if (!isRecord(before) || !isRecord(after))
67
+ return [];
68
+ const paths = [];
69
+ for (const [key, value] of Object.entries(before)) {
70
+ const path = prefix ? `${prefix}.${key}` : key;
71
+ if (!(key in after)) {
72
+ paths.push(path);
73
+ continue;
74
+ }
75
+ paths.push(...strippedPaths(value, after[key], path));
76
+ }
77
+ return paths;
78
+ }
79
+ function validateHandlerOutput(schema, data, onStripped) {
80
+ const parsed = schema.safeParse(data);
81
+ if (parsed.success) {
82
+ if (onStripped) {
83
+ const paths = strippedPaths(data, parsed.data, "");
84
+ if (paths.length > 0)
85
+ onStripped(paths);
86
+ }
87
+ return { ok: true, data: parsed.data };
88
+ }
89
+ return {
90
+ ok: false,
91
+ message: `Handler output does not match the contract: ${formatZodError(parsed.error)}`
92
+ };
93
+ }
94
+ function validateDeclaredOutput(schema, data, onStripped) {
95
+ if (!schema) {
96
+ if (data === undefined || data === null)
97
+ return { ok: true, data };
98
+ return {
99
+ ok: false,
100
+ message: "Handler returned data but the contract declares no output"
101
+ };
102
+ }
103
+ if (data === undefined) {
104
+ return {
105
+ ok: false,
106
+ message: "Handler returned undefined but the contract declares an output"
107
+ };
108
+ }
109
+ return validateHandlerOutput(schema, data, onStripped);
110
+ }
111
+
112
+ // src/observability/trace.ts
113
+ var TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(.*)$/i;
114
+ function randomHex(bytes) {
115
+ const arr = new Uint8Array(bytes);
116
+ crypto.getRandomValues(arr);
117
+ let hex = "";
118
+ for (const byte of arr)
119
+ hex += byte.toString(16).padStart(2, "0");
120
+ return hex;
121
+ }
122
+ function createTraceContext() {
123
+ return { traceId: randomHex(16), spanId: randomHex(8) };
124
+ }
125
+ function parseTraceparent(header) {
126
+ if (!header)
127
+ return null;
128
+ const match = TRACEPARENT_RE.exec(header.trim());
129
+ if (!match?.[1] || !match[2] || !match[3] || !match[4] || match[5] === undefined)
130
+ return null;
131
+ const version = match[1].toLowerCase();
132
+ if (version === "ff")
133
+ return null;
134
+ const suffix = match[5];
135
+ if (version === "00" ? suffix !== "" : suffix !== "" && !/^(?:-[0-9a-f]{2,})+$/i.test(suffix)) {
136
+ return null;
137
+ }
138
+ const traceId = match[2].toLowerCase();
139
+ const parentSpanId = match[3].toLowerCase();
140
+ const traceFlags = match[4].toLowerCase();
141
+ if (/^0+$/.test(traceId) || /^0+$/.test(parentSpanId))
142
+ return null;
143
+ return { traceId, spanId: randomHex(8), parentSpanId, traceFlags };
144
+ }
145
+ function formatTraceparent(ctx) {
146
+ return `00-${ctx.traceId}-${ctx.spanId}-${ctx.traceFlags ?? "01"}`;
147
+ }
148
+ function resolveTraceContext(req) {
149
+ return parseTraceparent(req.headers.get("traceparent")) ?? createTraceContext();
150
+ }
151
+ function childSpan(parent) {
152
+ return {
153
+ traceId: parent.traceId,
154
+ spanId: randomHex(8),
155
+ parentSpanId: parent.spanId,
156
+ ...parent.tracestate !== undefined && { tracestate: parent.tracestate },
157
+ ...parent.baggage !== undefined && { baggage: parent.baggage },
158
+ ...parent.traceFlags !== undefined && { traceFlags: parent.traceFlags }
159
+ };
160
+ }
161
+ var encoder = new TextEncoder;
162
+ function boundedPropagationValue(value, maxBytes, maxMembers) {
163
+ if (typeof value !== "string")
164
+ return;
165
+ const trimmed = value.trim();
166
+ if (!trimmed || encoder.encode(trimmed).byteLength > maxBytes)
167
+ return;
168
+ for (const character of trimmed) {
169
+ const code = character.charCodeAt(0);
170
+ if (code <= 31 || code === 127)
171
+ return;
172
+ }
173
+ const members = trimmed.split(",");
174
+ if (members.length > maxMembers || members.some((member) => !member.trim())) {
175
+ return;
176
+ }
177
+ return trimmed;
178
+ }
179
+ function resolvePropagationContext(metadata, fallback) {
180
+ const traceparent = metadata?.traceparent;
181
+ const parsed = typeof traceparent === "string" ? parseTraceparent(traceparent) : null;
182
+ const trace = traceparent === undefined ? fallback ?? createTraceContext() : parsed ?? createTraceContext();
183
+ const tracestate = parsed ? boundedPropagationValue(metadata?.tracestate, 512, 32) : undefined;
184
+ const baggage = boundedPropagationValue(metadata?.baggage, 8192, 180);
185
+ return {
186
+ ...trace,
187
+ ...tracestate !== undefined && { tracestate },
188
+ ...baggage !== undefined && { baggage }
189
+ };
190
+ }
191
+
192
+ export { formatZodError, zodIssues, errorCode, recordedErrorMessage, normalizeError, validateDeclaredOutput, createTraceContext, parseTraceparent, formatTraceparent, resolveTraceContext, childSpan, resolvePropagationContext };
@@ -2,20 +2,20 @@ import {
2
2
  contextContributionDelta,
3
3
  mergeContextContribution,
4
4
  prepareContextContribution
5
- } from "./index-hxh98zbm.js";
5
+ } from "./index-vbf2p6me.js";
6
6
  import {
7
7
  base64UrlToBytes,
8
8
  bytesToBase64Url,
9
9
  isUnsafeKey,
10
10
  safeJsonParse
11
- } from "./index-pgsyp3xh.js";
12
- import {
13
- isRecord
14
- } from "./index-qyrqwr4c.js";
11
+ } from "./index-vj3vvpaa.js";
15
12
  import {
16
13
  forbidden,
17
14
  unauthorized
18
15
  } from "./index-0w9abg87.js";
16
+ import {
17
+ isRecord
18
+ } from "./index-qyrqwr4c.js";
19
19
 
20
20
  // src/server/middleware/cookies.ts
21
21
  function parseCookies(header) {
@@ -0,0 +1,63 @@
1
+ // src/agent-runtime/terminal-status.ts
2
+ function isSpeakableAssistantStatus(status) {
3
+ return status === "completed" || status === "interrupted" || status === "committed";
4
+ }
5
+ function isAssistantHistoryEvidence(status, policy) {
6
+ return isSpeakableAssistantStatus(status) || status === "failed" && policy?.failedAssistant === "assistant-marked";
7
+ }
8
+ function isCompleteAgentHistoryTurn(messages, policy) {
9
+ if (messages[0]?.role !== "user")
10
+ return false;
11
+ const calls = new Set;
12
+ const completed = new Set;
13
+ const approvals = new Map;
14
+ let assistantCount = 0;
15
+ for (const message of messages) {
16
+ if (message.role === "assistant") {
17
+ if (!isAssistantHistoryEvidence(message.status, policy))
18
+ return false;
19
+ assistantCount += 1;
20
+ }
21
+ for (const part of message.parts) {
22
+ if (part.type === "tool-call") {
23
+ if (calls.has(part.callId))
24
+ return false;
25
+ calls.add(part.callId);
26
+ } else if (part.type === "tool-approval-request") {
27
+ if (!calls.has(part.callId) || completed.has(part.callId) || approvals.has(part.approvalId))
28
+ return false;
29
+ if ([...approvals.values()].some((approval) => approval.callId === part.callId))
30
+ return false;
31
+ approvals.set(part.approvalId, { callId: part.callId, answered: false });
32
+ } else if (part.type === "tool-approval-response") {
33
+ const approval = approvals.get(part.approvalId);
34
+ if (!approval || approval.answered)
35
+ return false;
36
+ approval.answered = true;
37
+ } else if (part.type === "tool-result") {
38
+ if (!calls.has(part.callId) || completed.has(part.callId))
39
+ return false;
40
+ const approval = [...approvals.values()].find((entry) => entry.callId === part.callId);
41
+ if (approval && !approval.answered)
42
+ return false;
43
+ completed.add(part.callId);
44
+ }
45
+ }
46
+ }
47
+ return assistantCount > 0 && calls.size === completed.size && [...approvals.values()].every((approval) => approval.answered);
48
+ }
49
+ function assistantStatus(reason) {
50
+ if (reason === "success" || reason === "policy_stop" || reason === "provider_stop") {
51
+ return "completed";
52
+ }
53
+ if (reason === "superseded")
54
+ return "superseded";
55
+ if (reason === "absorbed")
56
+ return "superseded";
57
+ if (reason === "interrupted" || reason === "cancelled" || reason === "shutdown") {
58
+ return "interrupted";
59
+ }
60
+ return "failed";
61
+ }
62
+
63
+ export { isAssistantHistoryEvidence, isCompleteAgentHistoryTurn, assistantStatus };