stitchkit 0.70.5 → 0.71.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 (76) hide show
  1. package/dist/agent-runtime/coding-tool-contract.d.ts +11 -1
  2. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -1
  3. package/dist/agent-runtime/coding-tool-files.d.ts.map +1 -1
  4. package/dist/agent-runtime/coding-tool-listing.d.ts +15 -0
  5. package/dist/agent-runtime/coding-tool-listing.d.ts.map +1 -0
  6. package/dist/agent-runtime/coding-tool-paths.d.ts.map +1 -1
  7. package/dist/agent-runtime/coding-tool-refusals.d.ts +59 -0
  8. package/dist/agent-runtime/coding-tool-refusals.d.ts.map +1 -0
  9. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -1
  10. package/dist/agent-runtime/coding-tools.d.ts +3 -1
  11. package/dist/agent-runtime/coding-tools.d.ts.map +1 -1
  12. package/dist/agent-runtime/compaction.d.ts +35 -0
  13. package/dist/agent-runtime/compaction.d.ts.map +1 -1
  14. package/dist/agent-runtime/contained-files.d.ts +21 -2
  15. package/dist/agent-runtime/contained-files.d.ts.map +1 -1
  16. package/dist/agent-runtime/provider-failure.d.ts +66 -0
  17. package/dist/agent-runtime/provider-failure.d.ts.map +1 -0
  18. package/dist/agent-runtime/purge.d.ts +28 -0
  19. package/dist/agent-runtime/purge.d.ts.map +1 -0
  20. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  21. package/dist/agent-runtime/runtime.d.ts +31 -1
  22. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  23. package/dist/agent-runtime/schemas.d.ts +1 -0
  24. package/dist/agent-runtime/schemas.d.ts.map +1 -1
  25. package/dist/agent-runtime/sqlite-purge.d.ts +7 -0
  26. package/dist/agent-runtime/sqlite-purge.d.ts.map +1 -0
  27. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  28. package/dist/agent-runtime/store-driver.d.ts +2 -0
  29. package/dist/agent-runtime/store-driver.d.ts.map +1 -1
  30. package/dist/agent-runtime/store-purge.d.ts +13 -0
  31. package/dist/agent-runtime/store-purge.d.ts.map +1 -0
  32. package/dist/agent-runtime/store.d.ts +3 -0
  33. package/dist/agent-runtime/store.d.ts.map +1 -1
  34. package/dist/agent-runtime-coding-tools.js +438 -124
  35. package/dist/agent-runtime-harness.js +4 -4
  36. package/dist/agent-runtime-openrouter.d.ts +19 -0
  37. package/dist/agent-runtime-openrouter.d.ts.map +1 -1
  38. package/dist/agent-runtime-openrouter.js +2 -1
  39. package/dist/agent-runtime-sqlite-bun.js +2 -2
  40. package/dist/agent-runtime-sqlite-node.js +2 -2
  41. package/dist/agent-runtime.d.ts +5 -2
  42. package/dist/agent-runtime.d.ts.map +1 -1
  43. package/dist/agent-runtime.js +128 -16
  44. package/dist/cli.js +5 -5
  45. package/dist/{index-cx84zg25.js → index-118v0z41.js} +1 -1
  46. package/dist/{index-jw81xr75.js → index-19eet1qx.js} +127 -51
  47. package/dist/{index-ejv31h14.js → index-7qy2ex0m.js} +1 -1
  48. package/dist/{index-9sx8tbz2.js → index-cksjz4eg.js} +50 -1
  49. package/dist/{index-trrf7nch.js → index-ezmn6ac6.js} +3 -3
  50. package/dist/{index-ekkt4gy9.js → index-jqtsc9mj.js} +2 -2
  51. package/dist/{index-hxtm2xr2.js → index-k2zczx1g.js} +1 -1
  52. package/dist/{index-35wcrke5.js → index-m668wzyc.js} +13 -2
  53. package/dist/{index-w9m1wznn.js → index-nemjkxjp.js} +118 -1
  54. package/dist/{index-tnazr5tc.js → index-pz7ytdga.js} +3 -3
  55. package/dist/{index-1z5xxfst.js → index-rqpdar1e.js} +102 -5
  56. package/dist/{index-qm87g51s.js → index-s4c8wy8m.js} +1 -1
  57. package/dist/node.js +2 -2
  58. package/dist/observability/index.js +1 -1
  59. package/dist/server/index.d.ts +1 -1
  60. package/dist/server/index.d.ts.map +1 -1
  61. package/dist/server/index.js +4 -2
  62. package/dist/server/request.d.ts +19 -0
  63. package/dist/server/request.d.ts.map +1 -1
  64. package/dist/telegram/init-data.d.ts +134 -0
  65. package/dist/telegram/init-data.d.ts.map +1 -0
  66. package/dist/telegram/send-failure.d.ts +73 -0
  67. package/dist/telegram/send-failure.d.ts.map +1 -0
  68. package/dist/telegram.d.ts +3 -0
  69. package/dist/telegram.d.ts.map +1 -0
  70. package/dist/telegram.js +224 -0
  71. package/dist/tool-invoker.js +4 -4
  72. package/dist/tools.js +7 -7
  73. package/llms-full.txt +332 -9
  74. package/native/darwin-arm64.node +0 -0
  75. package/native/darwin-x64.node +0 -0
  76. package/package.json +6 -2
@@ -30,19 +30,49 @@ var AgentConversationMessagePageSchema = z.object({
30
30
  nextCursor: z.string().min(1).optional()
31
31
  }).strict();
32
32
 
33
- // src/agent-runtime/store.ts
33
+ // src/agent-runtime/purge.ts
34
34
  import { z as z2 } from "zod";
35
- var AgentStoreConflictSchema = z2.object({
36
- outcome: z2.literal("conflict"),
35
+ var AgentConversationPurgeInputSchema = z2.strictObject({
36
+ conversationId: AgentRecordIdSchema,
37
+ expectedVersion: AgentRecordVersionSchema.optional()
38
+ });
39
+ var AgentConversationPurgeResultSchema = z2.discriminatedUnion("outcome", [
40
+ z2.strictObject({ outcome: z2.literal("purged") }),
41
+ z2.strictObject({ outcome: z2.literal("already_purged") }),
42
+ z2.strictObject({ outcome: z2.literal("unsupported") }),
43
+ z2.strictObject({
44
+ outcome: z2.literal("active"),
45
+ runIds: z2.array(AgentRecordIdSchema).min(1)
46
+ }),
47
+ z2.strictObject({ outcome: z2.literal("conflict"), actualVersion: AgentRecordVersionSchema })
48
+ ]);
49
+
50
+ class AgentConversationPurgedError extends Error {
51
+ constructor() {
52
+ super("Agent conversation has been purged; use a new conversation ID");
53
+ this.name = "AgentConversationPurgedError";
54
+ }
55
+ }
56
+ async function purgeAgentConversation(store, input) {
57
+ const parsed = AgentConversationPurgeInputSchema.parse(input);
58
+ if (!store.purgeConversation)
59
+ return { outcome: "unsupported" };
60
+ return AgentConversationPurgeResultSchema.parse(await store.purgeConversation(parsed));
61
+ }
62
+
63
+ // src/agent-runtime/store.ts
64
+ import { z as z3 } from "zod";
65
+ var AgentStoreConflictSchema = z3.object({
66
+ outcome: z3.literal("conflict"),
37
67
  actualVersion: AgentRecordVersionSchema
38
68
  });
39
- var AgentStoreNotFoundSchema = z2.object({ outcome: z2.literal("not_found") });
40
- var AgentStoreAppliedSchema = z2.object({
41
- outcome: z2.literal("applied"),
69
+ var AgentStoreNotFoundSchema = z3.object({ outcome: z3.literal("not_found") });
70
+ var AgentStoreAppliedSchema = z3.object({
71
+ outcome: z3.literal("applied"),
42
72
  snapshot: AgentSnapshotSchema
43
73
  });
44
- var AgentStoreDuplicateSchema = z2.object({
45
- outcome: z2.literal("duplicate"),
74
+ var AgentStoreDuplicateSchema = z3.object({
75
+ outcome: z3.literal("duplicate"),
46
76
  input: AgentMessageSchema,
47
77
  inputMessageId: AgentRecordIdSchema,
48
78
  runId: AgentRecordIdSchema,
@@ -51,116 +81,141 @@ var AgentStoreDuplicateSchema = z2.object({
51
81
  assistant: AgentMessageSchema.optional(),
52
82
  snapshot: AgentSnapshotSchema
53
83
  });
54
- var AgentStoreMutationResultSchema = z2.discriminatedUnion("outcome", [
84
+ var AgentStoreMutationResultSchema = z3.discriminatedUnion("outcome", [
55
85
  AgentStoreAppliedSchema,
56
86
  AgentStoreDuplicateSchema,
57
87
  AgentStoreConflictSchema,
58
88
  AgentStoreNotFoundSchema
59
89
  ]);
60
- var AgentRunViewSchema = z2.object({
90
+ var AgentRunViewSchema = z3.object({
61
91
  snapshotVersion: AgentRecordVersionSchema,
62
92
  run: AgentRunSchema,
63
93
  assistant: AgentMessageSchema.optional()
64
94
  });
65
- var AcceptInputAndAssignRunSchema = z2.object({
66
- idempotencyKey: z2.string().min(1),
95
+ var AcceptInputAndAssignRunSchema = z3.object({
96
+ idempotencyKey: z3.string().min(1),
67
97
  expectedVersion: AgentRecordVersionSchema.optional(),
68
98
  input: AgentMessageSchema,
69
99
  run: AgentRunSchema,
70
100
  coalesceIntoRunId: AgentRecordIdSchema.optional()
71
101
  });
72
- var AcquireAgentRunSchema = z2.object({
102
+ var AcquireAgentRunSchema = z3.object({
73
103
  conversationId: AgentRecordIdSchema,
74
104
  runId: AgentRecordIdSchema,
75
105
  expectedRevision: AgentRecordVersionSchema,
76
- ownerId: z2.string().min(1)
106
+ ownerId: z3.string().min(1)
77
107
  });
78
- var CheckpointRunAssistantSchema = z2.object({
108
+ var CheckpointRunAssistantSchema = z3.object({
79
109
  conversationId: AgentRecordIdSchema,
80
110
  runId: AgentRecordIdSchema,
81
111
  expectedRevision: AgentRecordVersionSchema,
82
- ownerId: z2.string().min(1),
112
+ ownerId: z3.string().min(1),
83
113
  fencingToken: AgentRecordVersionSchema.optional(),
84
114
  assistant: AgentMessageSchema,
85
115
  usage: AgentUsageSchema.optional()
86
116
  });
87
- var CommitRunTerminalSchema = z2.object({
117
+ var CommitRunTerminalSchema = z3.object({
88
118
  conversationId: AgentRecordIdSchema,
89
119
  runId: AgentRecordIdSchema,
90
120
  expectedRevision: AgentRecordVersionSchema,
91
- ownerId: z2.string().min(1),
121
+ ownerId: z3.string().min(1),
92
122
  fencingToken: AgentRecordVersionSchema.optional(),
93
123
  assistant: AgentMessageSchema,
94
124
  reason: AgentTerminalReasonSchema,
95
- policyName: z2.string().min(1).optional(),
125
+ policyName: z3.string().min(1).optional(),
96
126
  usage: AgentUsageSchema.optional(),
97
- absorb: z2.array(z2.object({
127
+ absorb: z3.array(z3.object({
98
128
  runId: AgentRecordIdSchema,
99
- inputMessageIds: z2.array(AgentRecordIdSchema).min(1)
129
+ inputMessageIds: z3.array(AgentRecordIdSchema).min(1)
100
130
  })).min(1).optional()
101
131
  });
102
- var RequestRunInterruptSchema = z2.object({
132
+ var RequestRunInterruptSchema = z3.object({
103
133
  conversationId: AgentRecordIdSchema,
104
134
  runId: AgentRecordIdSchema,
105
135
  expectedRevision: AgentRecordVersionSchema
106
136
  });
107
- var RecoverAgentRunSchema = z2.object({
137
+ var RecoverAgentRunSchema = z3.object({
108
138
  conversationId: AgentRecordIdSchema,
109
139
  runId: AgentRecordIdSchema,
110
140
  expectedRevision: AgentRecordVersionSchema,
111
- action: z2.enum(["requeue", "abandon"]),
112
- replaySafe: z2.boolean().optional()
141
+ action: z3.enum(["requeue", "abandon"]),
142
+ replaySafe: z3.boolean().optional()
113
143
  });
114
- var ReplaceCompactedRangeSchema = z2.object({
144
+ var ReplaceCompactedRangeSchema = z3.object({
115
145
  conversationId: AgentRecordIdSchema,
116
146
  expectedVersion: AgentRecordVersionSchema,
117
- replacedMessageIds: z2.array(AgentRecordIdSchema).min(1),
147
+ replacedMessageIds: z3.array(AgentRecordIdSchema).min(1),
118
148
  summary: AgentMessageSchema
119
149
  });
120
- var AgentRecoverableDescriptorSchema = z2.object({
150
+ var AgentRecoverableDescriptorSchema = z3.object({
121
151
  conversationId: AgentRecordIdSchema,
122
152
  run: AgentRunSchema
123
153
  });
124
- var AgentRecoverablePageSchema = z2.object({
125
- items: z2.array(AgentRecoverableDescriptorSchema),
126
- nextCursor: z2.string().min(1).optional()
154
+ var AgentRecoverablePageSchema = z3.object({
155
+ items: z3.array(AgentRecoverableDescriptorSchema),
156
+ nextCursor: z3.string().min(1).optional()
127
157
  });
128
158
 
129
159
  // src/agent-runtime/store-driver.ts
130
- import { z as z3 } from "zod";
131
- var AgentRuntimeHeadSchema = z3.object({
132
- schemaVersion: z3.literal(1),
160
+ import { z as z4 } from "zod";
161
+
162
+ // src/agent-runtime/store-purge.ts
163
+ function createStoreConversationPurge(driver, conversations) {
164
+ return async (input) => {
165
+ const { conversationId, expectedVersion } = AgentConversationPurgeInputSchema.parse(input);
166
+ return driver.transaction(async (transaction) => {
167
+ if (await conversations.isPurged(transaction, conversationId)) {
168
+ return { outcome: "already_purged" };
169
+ }
170
+ const head = await driver.head.load(transaction, conversationId);
171
+ const actualVersion = head?.version ?? 0;
172
+ if (expectedVersion !== undefined && expectedVersion !== actualVersion) {
173
+ return { outcome: "conflict", actualVersion };
174
+ }
175
+ const active = await driver.runs.listActive(transaction, conversationId);
176
+ if (active.length > 0) {
177
+ return { outcome: "active", runIds: active.map((record) => record.run.id) };
178
+ }
179
+ await conversations.remove(transaction, conversationId);
180
+ return { outcome: "purged" };
181
+ });
182
+ };
183
+ }
184
+
185
+ // src/agent-runtime/store-driver.ts
186
+ var AgentRuntimeHeadSchema = z4.object({
187
+ schemaVersion: z4.literal(1),
133
188
  conversationId: AgentRecordIdSchema,
134
189
  version: AgentRecordVersionSchema
135
190
  });
136
- var AgentStoredRunSchema = z3.object({
137
- schemaVersion: z3.literal(1),
191
+ var AgentStoredRunSchema = z4.object({
192
+ schemaVersion: z4.literal(1),
138
193
  run: AgentRunSchema,
139
194
  terminalAssistant: AgentMessageSchema.optional()
140
195
  });
141
- var AgentAdmissionReceiptSchema = z3.object({
142
- schemaVersion: z3.literal(1),
196
+ var AgentAdmissionReceiptSchema = z4.object({
197
+ schemaVersion: z4.literal(1),
143
198
  conversationId: AgentRecordIdSchema,
144
- idempotencyKey: z3.string().min(1),
199
+ idempotencyKey: z4.string().min(1),
145
200
  input: AgentMessageSchema,
146
201
  runId: AgentRecordIdSchema,
147
202
  assistantMessageId: AgentRecordIdSchema
148
203
  });
149
- var AgentHistoryMutationSchema = z3.discriminatedUnion("type", [
150
- z3.object({ type: z3.literal("admit"), input: AgentMessageSchema }),
151
- z3.object({
152
- type: z3.literal("upsert-assistant"),
204
+ var AgentHistoryMutationSchema = z4.discriminatedUnion("type", [
205
+ z4.object({ type: z4.literal("admit"), input: AgentMessageSchema }),
206
+ z4.object({
207
+ type: z4.literal("upsert-assistant"),
153
208
  message: AgentMessageSchema
154
209
  }),
155
- z3.object({
156
- type: z3.literal("replace-compacted-range"),
157
- replacedMessageIds: z3.array(AgentRecordIdSchema).min(1),
210
+ z4.object({
211
+ type: z4.literal("replace-compacted-range"),
212
+ replacedMessageIds: z4.array(AgentRecordIdSchema).min(1),
158
213
  summary: AgentMessageSchema
159
214
  })
160
215
  ]);
161
- var AgentRecoverableScanInputSchema = z3.object({
162
- cursor: z3.string().min(1).optional(),
163
- limit: z3.number().int().min(1).max(1000)
216
+ var AgentRecoverableScanInputSchema = z4.object({
217
+ cursor: z4.string().min(1).optional(),
218
+ limit: z4.number().int().min(1).max(1000)
164
219
  });
165
220
  function emptyHead(conversationId) {
166
221
  return AgentRuntimeHeadSchema.parse({
@@ -264,7 +319,7 @@ function validateSnapshot(head, messages, records) {
264
319
  }
265
320
  }
266
321
  }
267
- var RecoverableCursorSchema = z3.tuple([AgentRecordIdSchema, AgentRecordIdSchema]);
322
+ var RecoverableCursorSchema = z4.tuple([AgentRecordIdSchema, AgentRecordIdSchema]);
268
323
  function recoverableCursor(input) {
269
324
  return JSON.stringify([input.conversationId, input.run.id]);
270
325
  }
@@ -622,6 +677,9 @@ function createAgentRuntimeStore(driver) {
622
677
  });
623
678
  const mutate = (operation) => driver.transaction(async (transaction) => {
624
679
  const conversationId = operationConversationId(operation);
680
+ if (await driver.conversations?.isPurged(transaction, conversationId)) {
681
+ throw new AgentConversationPurgedError;
682
+ }
625
683
  const operationRunId = operation.type === "accept" ? operation.input.coalesceIntoRunId : operation.type === "compact" ? undefined : operation.input.runId;
626
684
  const [stored, messages, activeRecords, operationRecord, duplicateReceipt] = await Promise.all([
627
685
  driver.head.load(transaction, conversationId),
@@ -724,6 +782,9 @@ function createAgentRuntimeStore(driver) {
724
782
  loadSnapshot,
725
783
  loadRun,
726
784
  listActiveRuns,
785
+ ...driver.conversations && {
786
+ purgeConversation: createStoreConversationPurge(driver, driver.conversations)
787
+ },
727
788
  acceptInputAndAssignRun: (input) => mutate({
728
789
  type: "accept",
729
790
  input: AcceptInputAndAssignRunSchema.parse(input)
@@ -768,6 +829,7 @@ function cloneHistoryMap(source) {
768
829
  ]));
769
830
  }
770
831
  function createMemoryAgentRuntimeStore() {
832
+ let purged = new Set;
771
833
  let heads = new Map;
772
834
  let runs = new Map;
773
835
  let admissions = new Map;
@@ -784,6 +846,7 @@ function createMemoryAgentRuntimeStore() {
784
846
  return;
785
847
  });
786
848
  const transaction = {
849
+ purged: new Set(purged),
787
850
  heads: cloneHeadMap(heads),
788
851
  runs: cloneNestedMap(runs, (record) => AgentStoredRunSchema.parse(structuredClone(record))),
789
852
  admissions: cloneNestedMap(admissions, (receipt) => AgentAdmissionReceiptSchema.parse(structuredClone(receipt))),
@@ -791,6 +854,7 @@ function createMemoryAgentRuntimeStore() {
791
854
  };
792
855
  try {
793
856
  const result = await work(transaction);
857
+ purged = transaction.purged;
794
858
  heads = transaction.heads;
795
859
  runs = transaction.runs;
796
860
  admissions = transaction.admissions;
@@ -800,6 +864,18 @@ function createMemoryAgentRuntimeStore() {
800
864
  release.resolve();
801
865
  }
802
866
  },
867
+ conversations: {
868
+ async isPurged(transaction, conversationId) {
869
+ return transaction.purged.has(conversationId);
870
+ },
871
+ async remove(transaction, conversationId) {
872
+ transaction.purged.add(conversationId);
873
+ transaction.heads.delete(conversationId);
874
+ transaction.runs.delete(conversationId);
875
+ transaction.admissions.delete(conversationId);
876
+ transaction.histories.delete(conversationId);
877
+ }
878
+ },
803
879
  head: {
804
880
  async load(transaction, conversationId) {
805
881
  const head = transaction.heads.get(conversationId);
@@ -912,4 +988,4 @@ function createMemoryAgentRuntimeStore() {
912
988
  return createAgentRuntimeStore(driver);
913
989
  }
914
990
 
915
- export { AgentConversationSummarySchema, AgentConversationPageSchema, AgentConversationMessagePageSchema, AgentStoreConflictSchema, AgentStoreNotFoundSchema, AgentStoreAppliedSchema, AgentStoreDuplicateSchema, AgentStoreMutationResultSchema, AgentRunViewSchema, AcceptInputAndAssignRunSchema, AcquireAgentRunSchema, CheckpointRunAssistantSchema, CommitRunTerminalSchema, RequestRunInterruptSchema, RecoverAgentRunSchema, ReplaceCompactedRangeSchema, AgentRecoverableDescriptorSchema, AgentRecoverablePageSchema, AgentRuntimeHeadSchema, AgentStoredRunSchema, AgentAdmissionReceiptSchema, AgentHistoryMutationSchema, ACTIVE_AGENT_RUN_STATES, createAgentRuntimeStore, createMemoryAgentRuntimeStore };
991
+ export { AgentConversationSummarySchema, AgentConversationPageSchema, AgentConversationMessagePageSchema, AgentConversationPurgeInputSchema, AgentConversationPurgeResultSchema, AgentConversationPurgedError, purgeAgentConversation, AgentStoreConflictSchema, AgentStoreNotFoundSchema, AgentStoreAppliedSchema, AgentStoreDuplicateSchema, AgentStoreMutationResultSchema, AgentRunViewSchema, AcceptInputAndAssignRunSchema, AcquireAgentRunSchema, CheckpointRunAssistantSchema, CommitRunTerminalSchema, RequestRunInterruptSchema, RecoverAgentRunSchema, ReplaceCompactedRangeSchema, AgentRecoverableDescriptorSchema, AgentRecoverablePageSchema, AgentRuntimeHeadSchema, AgentStoredRunSchema, AgentAdmissionReceiptSchema, AgentHistoryMutationSchema, ACTIVE_AGENT_RUN_STATES, createAgentRuntimeStore, createMemoryAgentRuntimeStore };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  executeToolMethod
3
- } from "./index-qm87g51s.js";
3
+ } from "./index-s4c8wy8m.js";
4
4
  import {
5
5
  assertToolExtensionCompatible,
6
6
  mergeSchemas,
@@ -8,7 +8,7 @@ import {
8
8
  AgentRuntimeHeadSchema,
9
9
  AgentStoredRunSchema,
10
10
  createAgentRuntimeStore
11
- } from "./index-jw81xr75.js";
11
+ } from "./index-19eet1qx.js";
12
12
  import {
13
13
  AgentMessageSchema,
14
14
  AgentRunSchema
@@ -16,6 +16,52 @@ import {
16
16
 
17
17
  // src/agent-runtime/sqlite.ts
18
18
  import { z } from "zod";
19
+
20
+ // src/agent-runtime/sqlite-purge.ts
21
+ var OWNED_TABLES = [
22
+ "stitchkit_agent_runtime_messages",
23
+ "stitchkit_agent_runtime_admissions",
24
+ "stitchkit_agent_runtime_runs",
25
+ "stitchkit_agent_runtime_heads"
26
+ ];
27
+ function initializeSqliteConversationPurge(database) {
28
+ database.exec(`
29
+ CREATE TABLE IF NOT EXISTS stitchkit_agent_runtime_purged (
30
+ conversation_id TEXT PRIMARY KEY
31
+ );
32
+ `);
33
+ for (const table of OWNED_TABLES) {
34
+ for (const operation of ["INSERT", "UPDATE"]) {
35
+ database.exec(`
36
+ CREATE TRIGGER IF NOT EXISTS ${table}_purge_${operation.toLowerCase()}
37
+ BEFORE ${operation} ON ${table}
38
+ WHEN EXISTS (
39
+ SELECT 1 FROM stitchkit_agent_runtime_purged WHERE conversation_id = NEW.conversation_id
40
+ )
41
+ BEGIN SELECT RAISE(ABORT, 'Agent conversation has been purged'); END;
42
+ `);
43
+ }
44
+ }
45
+ }
46
+ function sqliteConversationPurge(database) {
47
+ const table = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stitchkit_agent_runtime_purged'").get();
48
+ if (table === null || table === undefined)
49
+ return;
50
+ return {
51
+ async isPurged(transaction, conversationId) {
52
+ const row = transaction.prepare("SELECT conversation_id FROM stitchkit_agent_runtime_purged WHERE conversation_id = ?").get(conversationId);
53
+ return row !== null && row !== undefined;
54
+ },
55
+ async remove(transaction, conversationId) {
56
+ transaction.prepare("INSERT INTO stitchkit_agent_runtime_purged (conversation_id) VALUES (?)").run(conversationId);
57
+ for (const table2 of OWNED_TABLES) {
58
+ transaction.prepare(`DELETE FROM ${table2} WHERE conversation_id = ?`).run(conversationId);
59
+ }
60
+ }
61
+ };
62
+ }
63
+
64
+ // src/agent-runtime/sqlite.ts
19
65
  var HeadRowSchema = z.object({ version: z.number().int().nonnegative() });
20
66
  var RunRowSchema = z.object({
21
67
  payload: z.string(),
@@ -121,6 +167,7 @@ function initializeAgentRuntimeSqlite(database) {
121
167
  if (missingTables.length > 0) {
122
168
  throw new Error(`Refusing a partial Stitchkit agent-runtime SQLite schema; missing ${missingTables.join(", ")}`);
123
169
  }
170
+ initializeSqliteConversationPurge(database);
124
171
  database.exec("COMMIT");
125
172
  return;
126
173
  }
@@ -165,6 +212,7 @@ function initializeAgentRuntimeSqlite(database) {
165
212
  );
166
213
  INSERT INTO stitchkit_agent_runtime_meta (key, value) VALUES ('schema_version', '1');
167
214
  `);
215
+ initializeSqliteConversationPurge(database);
168
216
  database.exec("COMMIT");
169
217
  } catch (error) {
170
218
  database.exec("ROLLBACK");
@@ -197,6 +245,7 @@ function createSqliteAgentRuntimeStore(config) {
197
245
  return result;
198
246
  };
199
247
  const driver = {
248
+ conversations: sqliteConversationPurge(database),
200
249
  transaction: (work) => serial(async () => {
201
250
  database.exec("BEGIN IMMEDIATE");
202
251
  try {
@@ -3,15 +3,15 @@ import {
3
3
  } from "./index-3xnq72rz.js";
4
4
  import {
5
5
  collectToolSurface
6
- } from "./index-hxtm2xr2.js";
6
+ } from "./index-k2zczx1g.js";
7
7
  import {
8
8
  createToolRunner,
9
9
  formatToolError
10
- } from "./index-ejv31h14.js";
10
+ } from "./index-7qy2ex0m.js";
11
11
  import {
12
12
  isToolExecutionControlError,
13
13
  toolResultFromError
14
- } from "./index-qm87g51s.js";
14
+ } from "./index-s4c8wy8m.js";
15
15
  import {
16
16
  isRecord
17
17
  } from "./index-qyrqwr4c.js";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  collectTools,
3
3
  createToolRunner
4
- } from "./index-ejv31h14.js";
4
+ } from "./index-7qy2ex0m.js";
5
5
  import {
6
6
  toolErrorFromResult
7
- } from "./index-qm87g51s.js";
7
+ } from "./index-s4c8wy8m.js";
8
8
  import {
9
9
  assertUniqueToolName
10
10
  } from "./index-22by16v6.js";
@@ -3,7 +3,7 @@ import {
3
3
  } from "./index-wwst0td5.js";
4
4
  import {
5
5
  contractToolMountable
6
- } from "./index-ejv31h14.js";
6
+ } from "./index-7qy2ex0m.js";
7
7
  import {
8
8
  projectToolSurface
9
9
  } from "./index-22by16v6.js";
@@ -15,7 +15,7 @@ import {
15
15
  import {
16
16
  ToolExecutionControlError,
17
17
  isToolExecutionControlError
18
- } from "./index-qm87g51s.js";
18
+ } from "./index-s4c8wy8m.js";
19
19
  import {
20
20
  AgentAssistantPlaceholderSchema,
21
21
  AgentJsonObjectSchema,
@@ -1418,11 +1418,18 @@ function createRunExecutor(dependencies) {
1418
1418
  ...run.fencingToken !== undefined && { fencingToken: run.fencingToken }
1419
1419
  })
1420
1420
  });
1421
+ let lastPromptTokens = { provenance: "unavailable" };
1421
1422
  const runtimeContext = {
1422
1423
  context: input.context,
1423
1424
  run,
1424
1425
  signal: executionSignal,
1425
- toolFenceLifecycle
1426
+ toolFenceLifecycle,
1427
+ get contextUsage() {
1428
+ const descriptor = selectedModel?.descriptor;
1429
+ if (!descriptor)
1430
+ return;
1431
+ return { usedTokens: lastPromptTokens, contextWindow: descriptor.contextWindow };
1432
+ }
1426
1433
  };
1427
1434
  selectedModel = await config.models.resolve({
1428
1435
  context: input.context,
@@ -1783,6 +1790,7 @@ function createRunExecutor(dependencies) {
1783
1790
  usage: part.usage,
1784
1791
  providerMetadata: part.providerMetadata
1785
1792
  }) ?? normalizeSdkUsage(part.usage);
1793
+ lastPromptTokens = stepUsage.inputTokens;
1786
1794
  modelUsage = addUsage(modelUsage, stepUsage);
1787
1795
  usage = nonModelUsage ? addUsage(nonModelUsage, modelUsage) : modelUsage;
1788
1796
  config.observe?.emit({
@@ -2182,6 +2190,9 @@ function createAgentRuntime(config) {
2182
2190
  updatedAt: nowIso
2183
2191
  });
2184
2192
  const outerAccepted = Promise.withResolvers();
2193
+ outerAccepted.promise.catch(() => {
2194
+ return;
2195
+ });
2185
2196
  const outerAdmission = Promise.withResolvers();
2186
2197
  outerAdmission.promise.catch(() => {
2187
2198
  return;
@@ -59,6 +59,123 @@ function parseQueryParams(url) {
59
59
  }
60
60
  return query;
61
61
  }
62
+ var IPV4_RESERVED = [
63
+ ["0.0.0.0", 8],
64
+ ["10.0.0.0", 8],
65
+ ["100.64.0.0", 10],
66
+ ["127.0.0.0", 8],
67
+ ["169.254.0.0", 16],
68
+ ["172.16.0.0", 12],
69
+ ["192.0.0.0", 24],
70
+ ["192.0.2.0", 24],
71
+ ["192.88.99.0", 24],
72
+ ["192.168.0.0", 16],
73
+ ["198.18.0.0", 15],
74
+ ["198.51.100.0", 24],
75
+ ["203.0.113.0", 24],
76
+ ["224.0.0.0", 4],
77
+ ["240.0.0.0", 4]
78
+ ];
79
+ function parseIpv4(value) {
80
+ const parts = value.split(".");
81
+ if (parts.length !== 4)
82
+ return;
83
+ let result = 0;
84
+ for (const part of parts) {
85
+ if (!/^(0|[1-9]\d{0,2})$/.test(part))
86
+ return;
87
+ const octet = Number(part);
88
+ if (octet > 255)
89
+ return;
90
+ result = result * 256 + octet;
91
+ }
92
+ return result;
93
+ }
94
+ function parseIpv6(value) {
95
+ const address = value.split("%")[0] ?? "";
96
+ if (!address.includes(":"))
97
+ return;
98
+ const halves = address.split("::");
99
+ if (halves.length > 2)
100
+ return;
101
+ const groups = [];
102
+ const tail = [];
103
+ const push = (into, text) => {
104
+ if (text === "")
105
+ return true;
106
+ for (const piece of text.split(":")) {
107
+ if (piece.includes(".")) {
108
+ const v4 = parseIpv4(piece);
109
+ if (v4 === undefined)
110
+ return false;
111
+ into.push(v4 >>> 16 & 65535, v4 & 65535);
112
+ continue;
113
+ }
114
+ if (!/^[0-9a-fA-F]{1,4}$/.test(piece))
115
+ return false;
116
+ into.push(Number.parseInt(piece, 16));
117
+ }
118
+ return true;
119
+ };
120
+ if (!push(groups, halves[0] ?? ""))
121
+ return;
122
+ if (halves.length === 2 && !push(tail, halves[1] ?? ""))
123
+ return;
124
+ const missing = 8 - groups.length - tail.length;
125
+ if (halves.length === 2 ? missing < 0 : missing !== 0)
126
+ return;
127
+ const words = [
128
+ ...groups,
129
+ ...Array(halves.length === 2 ? missing : 0).fill(0),
130
+ ...tail
131
+ ];
132
+ if (words.length !== 8)
133
+ return;
134
+ const bytes = new Uint8Array(16);
135
+ words.forEach((word, index) => {
136
+ bytes[index * 2] = word >>> 8 & 255;
137
+ bytes[index * 2 + 1] = word & 255;
138
+ });
139
+ return bytes;
140
+ }
141
+ function hasPrefix(bytes, prefix, bits) {
142
+ for (let index = 0;index < bits; index += 1) {
143
+ const byte = bytes[index >> 3] ?? 0;
144
+ const against = prefix[index >> 3] ?? 0;
145
+ const mask = 128 >> index % 8;
146
+ if ((byte & mask) !== (against & mask))
147
+ return false;
148
+ }
149
+ return true;
150
+ }
151
+ function isPublicIp(value) {
152
+ const address = value.trim();
153
+ if (!address)
154
+ return false;
155
+ const v4 = parseIpv4(address);
156
+ if (v4 !== undefined) {
157
+ return !IPV4_RESERVED.some(([network, bits]) => {
158
+ const base = parseIpv4(network);
159
+ if (base === undefined)
160
+ return false;
161
+ const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
162
+ return (v4 & mask) >>> 0 === (base & mask) >>> 0;
163
+ });
164
+ }
165
+ const bytes = parseIpv6(address);
166
+ if (!bytes)
167
+ return false;
168
+ if (hasPrefix(bytes, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255], 96)) {
169
+ return isPublicIp(Array.from(bytes.slice(12)).join("."));
170
+ }
171
+ if (!hasPrefix(bytes, [32], 3))
172
+ return false;
173
+ if (hasPrefix(bytes, [32, 1, 0, 0], 23))
174
+ return false;
175
+ if (hasPrefix(bytes, [32, 1, 13, 184], 32))
176
+ return false;
177
+ return true;
178
+ }
62
179
 
63
180
  // src/observability/context.ts
64
181
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -114,4 +231,4 @@ function wrapInRequestContext(handler, options = {}) {
114
231
  };
115
232
  }
116
233
 
117
- export { generateTraceId, resolveTraceId, resolveSocketIp, extractIp, getClientInfo, parseQueryParams, runWithRequestContext, getRequestContext, getTraceId, getUserId, setRequestUser, setRequestEndpoint, setRequestDimensions, setRequestError, wrapInRequestContext };
234
+ export { generateTraceId, resolveTraceId, resolveSocketIp, extractIp, getClientInfo, parseQueryParams, isPublicIp, runWithRequestContext, getRequestContext, getTraceId, getUserId, setRequestUser, setRequestEndpoint, setRequestDimensions, setRequestError, wrapInRequestContext };
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  collectToolSurface
3
- } from "./index-hxtm2xr2.js";
3
+ } from "./index-k2zczx1g.js";
4
4
  import {
5
5
  createToolRunner,
6
6
  formatToolError
7
- } from "./index-ejv31h14.js";
7
+ } from "./index-7qy2ex0m.js";
8
8
  import {
9
9
  coerceJsonArgs,
10
10
  toolResultFromError
11
- } from "./index-qm87g51s.js";
11
+ } from "./index-s4c8wy8m.js";
12
12
  import {
13
13
  isWithinDir
14
14
  } from "./index-sbdmyz75.js";