@bastani/atomic 0.9.34-alpha.1 → 0.9.35-alpha.1

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 (31) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/CHANGELOG.md +6 -0
  4. package/dist/builtin/mcp/OAUTH.md +1 -1
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/web-access/package.json +1 -1
  8. package/dist/builtin/workflows/CHANGELOG.md +11 -0
  9. package/dist/builtin/workflows/package.json +1 -1
  10. package/dist/builtin/workflows/src/extension/index.bundle.mjs +209 -77
  11. package/dist/builtin/workflows/src/index.js +28 -9
  12. package/dist/core/compaction/utils.d.ts +6 -0
  13. package/dist/core/compaction/utils.d.ts.map +1 -1
  14. package/dist/core/compaction/utils.js +6 -7
  15. package/dist/core/compaction/utils.js.map +1 -1
  16. package/dist/extensions/codemode/tool.js +1 -1
  17. package/dist/extensions/codemode/tool.js.map +1 -1
  18. package/dist/extensions/mcp/client/oauth/errors.d.ts +3 -2
  19. package/dist/extensions/mcp/client/oauth/errors.d.ts.map +1 -1
  20. package/dist/extensions/mcp/client/oauth/errors.js +3 -1
  21. package/dist/extensions/mcp/client/oauth/errors.js.map +1 -1
  22. package/dist/extensions/mcp/client/oauth/flow.d.ts.map +1 -1
  23. package/dist/extensions/mcp/client/oauth/flow.js +5 -4
  24. package/dist/extensions/mcp/client/oauth/flow.js.map +1 -1
  25. package/docs/codemode.md +1 -1
  26. package/docs/compaction/reference.md +2 -1
  27. package/docs/models/reference.md +3 -1
  28. package/docs/sdk.md +11 -1
  29. package/docs/workflows/operations.md +3 -1
  30. package/npm-shrinkwrap.json +32 -32
  31. package/package.json +3 -3
@@ -981,6 +981,7 @@ class InMemoryDurableBackend {
981
981
  ...handle.invocationCwd !== undefined ? { invocationCwd: handle.invocationCwd } : existing?.handle.invocationCwd !== undefined ? { invocationCwd: existing.handle.invocationCwd } : {},
982
982
  ...handle.origin !== undefined ? { origin: handle.origin } : existing?.handle.origin !== undefined ? { origin: existing.handle.origin } : {},
983
983
  modelOwner: authoritativeOwner ? handle.modelOwner : existing?.handle.modelOwner ?? handle.modelOwner,
984
+ ...handle.releasedModelOwner !== undefined ? { releasedModelOwner: handle.releasedModelOwner } : {},
984
985
  ...handle.workflowCwd !== undefined ? { workflowCwd: handle.workflowCwd } : existing?.handle.workflowCwd !== undefined ? { workflowCwd: existing.handle.workflowCwd } : {},
985
986
  ...handle.repositoryRoot !== undefined ? { repositoryRoot: handle.repositoryRoot } : existing?.handle.repositoryRoot !== undefined ? { repositoryRoot: existing.handle.repositoryRoot } : {},
986
987
  ...handle.gitWorktreeRoot !== undefined ? { gitWorktreeRoot: handle.gitWorktreeRoot } : existing?.handle.gitWorktreeRoot !== undefined ? { gitWorktreeRoot: existing.handle.gitWorktreeRoot } : {},
@@ -1194,14 +1195,20 @@ class InMemoryDurableBackend {
1194
1195
  if (pendingPrompts !== undefined)
1195
1196
  this.promptReservations.delete(workflowId);
1196
1197
  }
1197
- async transitionWorkflowStatus(workflowId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner) {
1198
+ async transitionWorkflowStatus(workflowId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
1198
1199
  const record = this.workflows.get(workflowId);
1199
1200
  const current = record?.handle;
1200
1201
  if (current === undefined || !expected.includes(current.status) || expectedUpdatedAt !== undefined && current.updatedAt !== expectedUpdatedAt)
1201
1202
  return false;
1202
1203
  this.setWorkflowStatus(workflowId, status, pendingPrompts, resumable);
1203
- if (modelOwner !== undefined && record !== undefined)
1204
- record.handle = { ...record.handle, modelOwner };
1204
+ if (record !== undefined) {
1205
+ const { releasedModelOwner: _previousRelease, ...settled } = record.handle;
1206
+ record.handle = {
1207
+ ...settled,
1208
+ ...modelOwner !== undefined ? { modelOwner } : {},
1209
+ ...releasedModelOwner !== undefined ? { releasedModelOwner } : {}
1210
+ };
1211
+ }
1205
1212
  return true;
1206
1213
  }
1207
1214
  adjustPendingPrompts(workflowId, delta) {
@@ -1283,6 +1290,7 @@ class InMemoryDurableBackend {
1283
1290
  ...h.invocationCwd !== undefined ? { invocationCwd: h.invocationCwd } : {},
1284
1291
  ...h.origin !== undefined ? { origin: h.origin } : {},
1285
1292
  modelOwner: h.modelOwner,
1293
+ ...h.releasedModelOwner !== undefined ? { releasedModelOwner: h.releasedModelOwner } : {},
1286
1294
  ...h.workflowCwd !== undefined ? { workflowCwd: h.workflowCwd } : {},
1287
1295
  ...h.repositoryRoot !== undefined ? { repositoryRoot: h.repositoryRoot } : {},
1288
1296
  ...h.gitWorktreeRoot !== undefined ? { gitWorktreeRoot: h.gitWorktreeRoot } : {},
@@ -2829,6 +2837,7 @@ function encodeMetadata(metadata) {
2829
2837
  ...metadata.failedToolNodeId !== undefined ? { failedToolNodeId: metadata.failedToolNodeId } : {},
2830
2838
  ...metadata.origin !== undefined ? { origin: metadata.origin } : {},
2831
2839
  modelOwner: metadata.modelOwner,
2840
+ ...metadata.releasedModelOwner !== undefined ? { releasedModelOwner: metadata.releasedModelOwner } : {},
2832
2841
  ...metadata.invocationCwd !== undefined ? { invocationCwd: metadata.invocationCwd } : {},
2833
2842
  ...metadata.workflowCwd !== undefined ? { workflowCwd: metadata.workflowCwd } : {},
2834
2843
  ...metadata.repositoryRoot !== undefined ? { repositoryRoot: metadata.repositoryRoot } : {},
@@ -2877,7 +2886,7 @@ function parseDurableWorkflowMetadata(value, workflowId) {
2877
2886
  return;
2878
2887
  const possibleStages = coercePossibleStages(serialized.possibleStages);
2879
2888
  const metadata = value;
2880
- if (metadata.workflowId !== workflowId || typeof metadata.workflowId !== "string" || typeof metadata.name !== "string" || typeof metadata.inputs !== "object" || metadata.inputs === null || Array.isArray(metadata.inputs) || typeof metadata.status !== "string" || !isDurableWorkflowStatus(metadata.status) || typeof metadata.completedCheckpoints !== "number" || typeof metadata.createdAt !== "number" || typeof metadata.pendingPrompts !== "number" || typeof metadata.promptReservationEpoch !== "string" || typeof metadata.updatedAt !== "number" || metadata.ownerExecutorId !== undefined && typeof metadata.ownerExecutorId !== "string" || metadata.transitionClaimId !== undefined && typeof metadata.transitionClaimId !== "string" || metadata.legacyRecoveryPending !== undefined && metadata.legacyRecoveryPending !== true || metadata.sessionFile !== undefined && typeof metadata.sessionFile !== "string" || metadata.label !== undefined && typeof metadata.label !== "string" || metadata.rootWorkflowId !== undefined && typeof metadata.rootWorkflowId !== "string" || metadata.resumable !== undefined && typeof metadata.resumable !== "boolean" || metadata.exited !== undefined && typeof metadata.exited !== "boolean" || metadata.exitReason !== undefined && typeof metadata.exitReason !== "string" || metadata.error !== undefined && typeof metadata.error !== "string" || metadata.failureKind !== undefined && !isWorkflowFailureKind(metadata.failureKind) || metadata.failureCode !== undefined && !isWorkflowFailureCode(metadata.failureCode) || metadata.failureRecoverability !== undefined && !isWorkflowFailureRecoverability(metadata.failureRecoverability) || metadata.failureDisposition !== undefined && !isWorkflowFailureDisposition(metadata.failureDisposition) || metadata.failedToolNodeId !== undefined && typeof metadata.failedToolNodeId !== "string" || metadata.invocationCwd !== undefined && typeof metadata.invocationCwd !== "string" || metadata.workflowCwd !== undefined && typeof metadata.workflowCwd !== "string" || metadata.repositoryRoot !== undefined && typeof metadata.repositoryRoot !== "string" || metadata.gitWorktreeRoot !== undefined && typeof metadata.gitWorktreeRoot !== "string")
2889
+ if (metadata.workflowId !== workflowId || typeof metadata.workflowId !== "string" || typeof metadata.name !== "string" || typeof metadata.inputs !== "object" || metadata.inputs === null || Array.isArray(metadata.inputs) || typeof metadata.status !== "string" || !isDurableWorkflowStatus(metadata.status) || typeof metadata.completedCheckpoints !== "number" || typeof metadata.createdAt !== "number" || typeof metadata.pendingPrompts !== "number" || typeof metadata.promptReservationEpoch !== "string" || typeof metadata.updatedAt !== "number" || metadata.ownerExecutorId !== undefined && typeof metadata.ownerExecutorId !== "string" || metadata.transitionClaimId !== undefined && typeof metadata.transitionClaimId !== "string" || metadata.legacyRecoveryPending !== undefined && metadata.legacyRecoveryPending !== true || metadata.sessionFile !== undefined && typeof metadata.sessionFile !== "string" || metadata.label !== undefined && typeof metadata.label !== "string" || metadata.rootWorkflowId !== undefined && typeof metadata.rootWorkflowId !== "string" || metadata.resumable !== undefined && typeof metadata.resumable !== "boolean" || metadata.exited !== undefined && typeof metadata.exited !== "boolean" || metadata.exitReason !== undefined && typeof metadata.exitReason !== "string" || metadata.error !== undefined && typeof metadata.error !== "string" || metadata.failureKind !== undefined && !isWorkflowFailureKind(metadata.failureKind) || metadata.failureCode !== undefined && !isWorkflowFailureCode(metadata.failureCode) || metadata.failureRecoverability !== undefined && !isWorkflowFailureRecoverability(metadata.failureRecoverability) || metadata.failureDisposition !== undefined && !isWorkflowFailureDisposition(metadata.failureDisposition) || metadata.failedToolNodeId !== undefined && typeof metadata.failedToolNodeId !== "string" || metadata.releasedModelOwner !== undefined && typeof metadata.releasedModelOwner !== "string" || metadata.invocationCwd !== undefined && typeof metadata.invocationCwd !== "string" || metadata.workflowCwd !== undefined && typeof metadata.workflowCwd !== "string" || metadata.repositoryRoot !== undefined && typeof metadata.repositoryRoot !== "string" || metadata.gitWorktreeRoot !== undefined && typeof metadata.gitWorktreeRoot !== "string")
2881
2890
  return;
2882
2891
  const { origin, possibleStages: rawPossibleStages, ...metadataWithoutOrigin } = metadata;
2883
2892
  return {
@@ -34923,7 +34932,9 @@ async function configureDbosDurableBackend(config) {
34923
34932
  throw new Error("Existing workflow executor has no database ownership fence; restart the host before recovering workflows");
34924
34933
  let launch = owner.active?.launch ?? (() => sdk.launch());
34925
34934
  let checkReady;
34926
- if (existing === undefined) {
34935
+ if (existing === undefined || owner.active === undefined) {
34936
+ if (owner.executorFence?.closed)
34937
+ owner.executorId = undefined;
34927
34938
  const url = effectiveSystemDatabaseUrl(config?.systemDatabaseUrl);
34928
34939
  await Promise.resolve().then(() => init_dbos_admission_config());
34929
34940
  const database = configureAdmissionDatabase(sdk, {
@@ -35403,7 +35414,7 @@ class DbosDurableBackend {
35403
35414
  await this.writeMetadata(workflowId);
35404
35415
  });
35405
35416
  }
35406
- async transitionWorkflowStatus(workflowId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner) {
35417
+ async transitionWorkflowStatus(workflowId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
35407
35418
  this.ensureGeneration();
35408
35419
  let records = [];
35409
35420
  const transition = () => transitionDbosWorkflowStatus({
@@ -35420,13 +35431,14 @@ class DbosDurableBackend {
35420
35431
  const pendingPrompts = this.promptReservations.hydrate(workflowId, entry.pendingPrompts, records, entry.promptReservationEpoch);
35421
35432
  this.applyMetadata(workflowId, { ...entry, pendingPrompts });
35422
35433
  },
35423
- claim: (authoritative, generation) => this.claimStatusTransition(workflowId, authoritative, generation, status, pendingPrompts, resumable, modelOwner),
35434
+ claim: (authoritative, generation) => this.claimStatusTransition(workflowId, authoritative, generation, status, pendingPrompts, resumable, modelOwner, releasedModelOwner),
35424
35435
  write: async () => {
35425
35436
  const handle = this.mem.getWorkflow(workflowId);
35426
35437
  if (handle !== undefined)
35427
35438
  this.mem.registerWorkflow({
35428
35439
  ...handle,
35429
35440
  legacyRecoveryPending: undefined,
35441
+ releasedModelOwner,
35430
35442
  ...modelOwner !== undefined ? { modelOwner } : {}
35431
35443
  }, true);
35432
35444
  this.setWorkflowStatus(workflowId, status, pendingPrompts, resumable);
@@ -35438,7 +35450,7 @@ class DbosDurableBackend {
35438
35450
  await this.flush(workflowId);
35439
35451
  return await this.sdk.withWorkflowClaim(workflowId, transition);
35440
35452
  }
35441
- async claimStatusTransition(workflowId, authoritative, generation, status, pendingPrompts, resumable, modelOwner) {
35453
+ async claimStatusTransition(workflowId, authoritative, generation, status, pendingPrompts, resumable, modelOwner, releasedModelOwner) {
35442
35454
  const stepName = claimMetadataStepName(generation);
35443
35455
  const transitionClaimId = crypto.randomUUID();
35444
35456
  const claim = {
@@ -35447,6 +35459,7 @@ class DbosDurableBackend {
35447
35459
  ...pendingPrompts !== undefined ? { pendingPrompts } : {},
35448
35460
  ...resumable !== undefined ? { resumable } : {},
35449
35461
  ...modelOwner === undefined ? {} : { modelOwner },
35462
+ releasedModelOwner,
35450
35463
  legacyRecoveryPending: undefined,
35451
35464
  ownerExecutorId: this.executorId,
35452
35465
  transitionClaimId,
@@ -39062,8 +39075,11 @@ async function shutdownDbos() {
39062
39075
  }
39063
39076
  if (errors.length > 0)
39064
39077
  throw combinedShutdownFailure(errors);
39065
- if (wasReady)
39078
+ if (wasReady) {
39066
39079
  slot.state = "shut_down";
39080
+ slot.configured = undefined;
39081
+ slot.active = undefined;
39082
+ }
39067
39083
  })().catch(async (error) => {
39068
39084
  slot.failure = await durabilityFailure("shutdown", error);
39069
39085
  slot.state = "failed";
@@ -50677,6 +50693,9 @@ init_dbos_admission();
50677
50693
  init_dbos_sdk_handle();
50678
50694
  init_factory();
50679
50695
 
50696
+ // dist/builtin/workflows/src/durable/sdk-owner-release.ts
50697
+ var releasedRuns = new WeakMap;
50698
+
50680
50699
  // dist/builtin/workflows/src/durable/sdk-recovery-scope.ts
50681
50700
  init_dbos_owner_fence();
50682
50701
  init_dbos_sdk_handle();
@@ -33,6 +33,12 @@ export declare function formatFileOperations(readFiles: string[], modifiedFiles:
33
33
  *
34
34
  * Tool results are truncated to keep the summarization request within
35
35
  * reasonable token budgets. Full content is not needed for summarization.
36
+ *
37
+ * Thinking is omitted. Providers return summaries of the real reasoning, and
38
+ * replayed thinking is often not part of the model's live context: for example,
39
+ * a block that does not match its request is dropped. Including it can make the
40
+ * summarization request larger than the context it summarizes. Visible text,
41
+ * tool calls, and tool results record what happened.
36
42
  */
37
43
  export declare function serializeConversation(messages: Message[]): string;
38
44
  export declare const SUMMARIZATION_SYSTEM_PROMPT = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAMvD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAgB,aAAa,IAAI,cAAc,CAM9C;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAe9F;AAUD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAK1G;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAUzF;AAmBD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAqDjE;AAMD,eAAO,MAAM,2BAA2B,6TAEmF,CAAC;AAM5H,wFAAwF;AACxF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,EAAE,CASxE"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAMvD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACrB,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACpB;AAED,wBAAgB,aAAa,IAAI,cAAc,CAM9C;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAe9F;AAUD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG;IAAE,SAAS,EAAE,MAAM,EAAE,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAA;CAAE,CAK1G;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAUzF;AAmBD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CA+CjE;AAMD,eAAO,MAAM,2BAA2B,6TAEmF,CAAC;AAM5H,wFAAwF;AACxF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,EAAE,CASxE"}
@@ -89,6 +89,12 @@ function truncateForSummary(text, maxChars) {
89
89
  *
90
90
  * Tool results are truncated to keep the summarization request within
91
91
  * reasonable token budgets. Full content is not needed for summarization.
92
+ *
93
+ * Thinking is omitted. Providers return summaries of the real reasoning, and
94
+ * replayed thinking is often not part of the model's live context: for example,
95
+ * a block that does not match its request is dropped. Including it can make the
96
+ * summarization request larger than the context it summarizes. Visible text,
97
+ * tool calls, and tool results record what happened.
92
98
  */
93
99
  export function serializeConversation(messages) {
94
100
  const parts = [];
@@ -105,15 +111,11 @@ export function serializeConversation(messages) {
105
111
  }
106
112
  else if (msg.role === "assistant") {
107
113
  const textParts = [];
108
- const thinkingParts = [];
109
114
  const toolCalls = [];
110
115
  for (const block of msg.content) {
111
116
  if (block.type === "text") {
112
117
  textParts.push(block.text);
113
118
  }
114
- else if (block.type === "thinking") {
115
- thinkingParts.push(block.thinking);
116
- }
117
119
  else if (block.type === "toolCall") {
118
120
  const args = block.arguments;
119
121
  const argsStr = Object.entries(args)
@@ -122,9 +124,6 @@ export function serializeConversation(messages) {
122
124
  toolCalls.push(`${block.name}(${argsStr})`);
123
125
  }
124
126
  }
125
- if (thinkingParts.length > 0) {
126
- parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);
127
- }
128
127
  if (textParts.length > 0) {
129
128
  parts.push(`[Assistant]: ${textParts.join("\n")}`);
130
129
  }
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAgBH,MAAM,UAAU,aAAa;IAC5B,OAAO;QACN,IAAI,EAAE,IAAI,GAAG,EAAE;QACf,OAAO,EAAE,IAAI,GAAG,EAAE;QAClB,MAAM,EAAE,IAAI,GAAG,EAAE;KACjB,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAqB,EAAE,OAAuB;IACvF,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QACnC,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YAAE,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACnG,OAAO;IACR,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;QAAE,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gBACb,KAAK,CAAC,IAAI,CAAC,kBAAkB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,CAAC,EAAE,CAAC,CAAC;YACpF,CAAC;QACF,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3B,CAAC;AAED,+EAA+E;AAC/E,8BAA8B;AAC9B,+EAA+E;AAE/E,MAAM,CAAC,MAAM,2BAA2B,GAAG;;2HAEgF,CAAC;AAE5H,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAE/E,wFAAwF;AACxF,MAAM,UAAU,gBAAgB,CAAC,KAA0B;IAC1D,MAAM,MAAM,GAAG,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC;IAC9D,MAAM,MAAM,GAAgB,EAAE,CAAC;IAC/B,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACvC,IAAI,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC,GAAG,GAAG,CAAC;YAAE,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC;;YAC9C,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * Shared utilities for compaction and branch summarization.\n */\n\nimport type { Message } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { LineRange } from \"./compaction-types.js\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from direct and recorded nested tool calls.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role === \"toolResult\") {\n\t\tfor (const call of message.nestedCalls?.calls ?? []) addFileOp(call.name, call.arguments, fileOps);\n\t\treturn;\n\t}\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\taddFileOp(block.name, block.arguments as Record<string, unknown> | undefined, fileOps);\n\t}\n}\n\nfunction addFileOp(name: string, args: Record<string, unknown> | undefined, fileOps: FileOperations): void {\n\tconst path = typeof args?.path === \"string\" ? args.path : undefined;\n\tif (!path) return;\n\tif (name === \"read\") fileOps.read.add(path);\n\telse if (name === \"write\") fileOps.written.add(path);\n\telse if (name === \"edit\") fileOps.edited.add(path);\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst thinkingParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"thinking\") {\n\t\t\t\t\tthinkingParts.push(block.thinking);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (thinkingParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant thinking]: ${thinkingParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n\n// ============================================================================\n// Line Range Helpers\n// ============================================================================\n\n/** Collapse a sparse set of line numbers into ascending contiguous inclusive ranges. */\nexport function contiguousRanges(lines: ReadonlySet<number>): LineRange[] {\n\tconst sorted = [...lines].sort((left, right) => left - right);\n\tconst ranges: LineRange[] = [];\n\tfor (const line of sorted) {\n\t\tconst last = ranges[ranges.length - 1];\n\t\tif (last && line === last.end + 1) last.end = line;\n\t\telse ranges.push({ start: line, end: line });\n\t}\n\treturn ranges;\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/core/compaction/utils.ts"],"names":[],"mappings":"AAA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\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { LineRange } from \"./compaction-types.js\";\n\n// ============================================================================\n// File Operation Tracking\n// ============================================================================\n\nexport interface FileOperations {\n\tread: Set<string>;\n\twritten: Set<string>;\n\tedited: Set<string>;\n}\n\nexport function createFileOps(): FileOperations {\n\treturn {\n\t\tread: new Set(),\n\t\twritten: new Set(),\n\t\tedited: new Set(),\n\t};\n}\n\n/**\n * Extract file operations from direct and recorded nested tool calls.\n */\nexport function extractFileOpsFromMessage(message: AgentMessage, fileOps: FileOperations): void {\n\tif (message.role === \"toolResult\") {\n\t\tfor (const call of message.nestedCalls?.calls ?? []) addFileOp(call.name, call.arguments, fileOps);\n\t\treturn;\n\t}\n\tif (message.role !== \"assistant\") return;\n\tif (!(\"content\" in message) || !Array.isArray(message.content)) return;\n\n\tfor (const block of message.content) {\n\t\tif (typeof block !== \"object\" || block === null) continue;\n\t\tif (!(\"type\" in block) || block.type !== \"toolCall\") continue;\n\t\tif (!(\"arguments\" in block) || !(\"name\" in block)) continue;\n\n\t\taddFileOp(block.name, block.arguments as Record<string, unknown> | undefined, fileOps);\n\t}\n}\n\nfunction addFileOp(name: string, args: Record<string, unknown> | undefined, fileOps: FileOperations): void {\n\tconst path = typeof args?.path === \"string\" ? args.path : undefined;\n\tif (!path) return;\n\tif (name === \"read\") fileOps.read.add(path);\n\telse if (name === \"write\") fileOps.written.add(path);\n\telse if (name === \"edit\") fileOps.edited.add(path);\n}\n\n/**\n * Compute final file lists from file operations.\n * Returns readFiles (files only read, not modified) and modifiedFiles.\n */\nexport function computeFileLists(fileOps: FileOperations): { readFiles: string[]; modifiedFiles: string[] } {\n\tconst modified = new Set([...fileOps.edited, ...fileOps.written]);\n\tconst readOnly = [...fileOps.read].filter((f) => !modified.has(f)).sort();\n\tconst modifiedFiles = [...modified].sort();\n\treturn { readFiles: readOnly, modifiedFiles };\n}\n\n/**\n * Format file operations as XML tags for summary.\n */\nexport function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {\n\tconst sections: string[] = [];\n\tif (readFiles.length > 0) {\n\t\tsections.push(`<read-files>\\n${readFiles.join(\"\\n\")}\\n</read-files>`);\n\t}\n\tif (modifiedFiles.length > 0) {\n\t\tsections.push(`<modified-files>\\n${modifiedFiles.join(\"\\n\")}\\n</modified-files>`);\n\t}\n\tif (sections.length === 0) return \"\";\n\treturn `\\n\\n${sections.join(\"\\n\\n\")}`;\n}\n\n// ============================================================================\n// Message Serialization\n// ============================================================================\n\n/** Maximum characters for a tool result in serialized summaries. */\nconst TOOL_RESULT_MAX_CHARS = 2000;\n\n/**\n * Truncate text to a maximum character length for summarization.\n * Keeps the beginning and appends a truncation marker.\n */\nfunction truncateForSummary(text: string, maxChars: number): string {\n\tif (text.length <= maxChars) return text;\n\tconst truncatedChars = text.length - maxChars;\n\treturn `${text.slice(0, maxChars)}\\n\\n[... ${truncatedChars} more characters truncated]`;\n}\n\n/**\n * Serialize LLM messages to text for summarization.\n * This prevents the model from treating it as a conversation to continue.\n * Call convertToLlm() first to handle custom message types.\n *\n * Tool results are truncated to keep the summarization request within\n * reasonable token budgets. Full content is not needed for summarization.\n *\n * Thinking is omitted. Providers return summaries of the real reasoning, and\n * replayed thinking is often not part of the model's live context: for example,\n * a block that does not match its request is dropped. Including it can make the\n * summarization request larger than the context it summarizes. Visible text,\n * tool calls, and tool results record what happened.\n */\nexport function serializeConversation(messages: Message[]): string {\n\tconst parts: string[] = [];\n\n\tfor (const msg of messages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tconst content =\n\t\t\t\ttypeof msg.content === \"string\"\n\t\t\t\t\t? msg.content\n\t\t\t\t\t: msg.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t\tif (content) parts.push(`[User]: ${content}`);\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst textParts: string[] = [];\n\t\t\tconst toolCalls: string[] = [];\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\ttextParts.push(block.text);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst args = block.arguments as Record<string, unknown>;\n\t\t\t\t\tconst argsStr = Object.entries(args)\n\t\t\t\t\t\t.map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\ttoolCalls.push(`${block.name}(${argsStr})`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (textParts.length > 0) {\n\t\t\t\tparts.push(`[Assistant]: ${textParts.join(\"\\n\")}`);\n\t\t\t}\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tparts.push(`[Assistant tool calls]: ${toolCalls.join(\"; \")}`);\n\t\t\t}\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst content = msg.content\n\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\");\n\t\t\tif (content) {\n\t\t\t\tparts.push(`[Tool result]: ${truncateForSummary(content, TOOL_RESULT_MAX_CHARS)}`);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\n// ============================================================================\n// Summarization System Prompt\n// ============================================================================\n\nexport const SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;\n\n// ============================================================================\n// Line Range Helpers\n// ============================================================================\n\n/** Collapse a sparse set of line numbers into ascending contiguous inclusive ranges. */\nexport function contiguousRanges(lines: ReadonlySet<number>): LineRange[] {\n\tconst sorted = [...lines].sort((left, right) => left - right);\n\tconst ranges: LineRange[] = [];\n\tfor (const line of sorted) {\n\t\tconst last = ranges[ranges.length - 1];\n\t\tif (last && line === last.end + 1) last.end = line;\n\t\telse ranges.push({ start: line, end: line });\n\t}\n\treturn ranges;\n}\n"]}
@@ -33,7 +33,7 @@ export function getCodemodeCallableTools(tools) {
33
33
  const INTRO = `Run JavaScript that composes tool calls in a fresh QuickJS worker sandbox.
34
34
  Top-level await and return work. Use tools.name(args), or tools["raw-name"](args). Tool names normalize to JavaScript identifiers.
35
35
  No Node, filesystem, network, timers, modules or credentials are available directly. Calls go through session validation and permission hooks. They have real side effects and are not undone after script failure.
36
- Tools with output schemas resolve to structuredContent; others resolve to text. Failed or blocked calls throw. Scripts have a 256 MB memory limit.
36
+ Tools with output schemas resolve to structuredContent; others resolve to text. Failed or blocked calls throw, except that a tool with an output schema resolves with its structuredContent on failure too when it returned one; check its fields. Scripts have a 256 MB memory limit.
37
37
  Globals: ALL_TOOLS, text(value), image(base64DataUrlOrImageContent), exit(), console.log(...), store(key, value), load(key), await searchTools(query, {limit?, namespace?}), await describeTool(name), await describeNamespace(name).
38
38
  tools, ALL_TOOLS and searchTools() matches cover only script-callable tools. Model-only tools such as subagent, workflow, intercom, and ask_user_question are excluded from them, but you can still call them directly. searchTools() and describeTool() answer the exact name of an active model-only tool with a hint to call it directly, not from a script.
39
39
  With several text items, each starts with a ==> text N/M <== line. Console calls follow the other output in one <console_output> block, with one line per call.
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,iBAAiB,EA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AAE,yBAAyB,CAAC,EAAE,EAAE,OAAO,CAAC;QACnD,UAAU,EAAE,cAAc;QAC1B,QAAQ,EAAE,YAAY;QACtB,WAAW,EAAE,WAAW;QACxB,aAAa,EAAE,KAAK;QACpB,aAAa,EAAE,sFAAsF;QACrG,cAAc,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC;QAC7D,mBAAmB,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,WAAW,EAAE,uBAAuB,EAAE,EAAE;QAC5F,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CACjD,CAAC,MAAM,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,eAAe,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC;QACxF,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AACD,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAAyB,EAAE,EAChC,OAAO,GAAwB,EAAE;IAEjC,OAAO;QACN,GAAG,kBAAkB,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC;QAC5D,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,OAAO,CAAC;KACtD,CAAC;AACH,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.js\";\nimport type { ToolDefinition, ToolInfo, ToolLoadout, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport { SETTINGS_DEFAULTS } from \"../../core/settings-defaults.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { codemodeRenderers } from \"./renderer.js\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\nexport const DEFAULT_CODEMODE_INLINE_BUDGET: number = SETTINGS_DEFAULTS.codemode.inlineBudget;\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\nexport interface CodemodeToolOptions {\n\tgetToolNamespace?: (name: string) => ToolNamespace | undefined;\n\t/** Prompt guidelines shown with tool declarations in describeTool() and ALL_TOOLS. */\n\tgetToolGuidelines?: () => ReadonlyMap<string, readonly string[]>;\n\tmodels?: boolean;\n\tappendEntry?: (type: string, data: CodemodeStoreEntryData) => void;\n\tgetMode?: () => CodemodeMode;\n\tgetInlineBudget?: () => number | undefined;\n\t/** Active model-only tools. Scripts cannot call them, so discovery answers an exact name with a hint. */\n\tgetModelOnlyTools?: () => readonly string[];\n}\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription:\n\t\t\t'Raw JavaScript source with top-level await and return. Optional first line // @options: {\"max_output_tokens\": 1000, \"timeout_ms\": 60000}',\n\t}),\n});\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\nexport interface CodemodeNestedCall {\n\tid: string;\n\tname: string;\n\targs: string;\n\tstatus: \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\tdurationMs?: number;\n\terror?: string;\n\tcost?: number;\n}\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\tfullOutputPath?: string;\n}\nexport function toCodemodeDeclaration(\n\ttool: AgentTool,\n\tguidelines: readonly string[] = [],\n): Omit<CodemodeTool, \"execute\"> {\n\tconst bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: bullets.length > 0 ? `${tool.description.trim()}\\n\\n${bullets.join(\"\\n\")}` : tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? { type: \"string\" },\n\t};\n}\nexport function getCodemodeCallableTools(tools: readonly AgentTool[]): AgentTool[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\nexport interface CodemodeDescriptionOptions {\n\tmodels?: boolean;\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\tdeferred?: ReadonlySet<string>;\n\tguidelines?: ReadonlyMap<string, readonly string[]>;\n\tinlineBudget?: number;\n}\nconst INTRO = `Run JavaScript that composes tool calls in a fresh QuickJS worker sandbox.\nTop-level await and return work. Use tools.name(args), or tools[\"raw-name\"](args). Tool names normalize to JavaScript identifiers.\nNo Node, filesystem, network, timers, modules or credentials are available directly. Calls go through session validation and permission hooks. They have real side effects and are not undone after script failure.\nTools with output schemas resolve to structuredContent; others resolve to text. Failed or blocked calls throw. Scripts have a 256 MB memory limit.\nGlobals: ALL_TOOLS, text(value), image(base64DataUrlOrImageContent), exit(), console.log(...), store(key, value), load(key), await searchTools(query, {limit?, namespace?}), await describeTool(name), await describeNamespace(name).\ntools, ALL_TOOLS and searchTools() matches cover only script-callable tools. Model-only tools such as subagent, workflow, intercom, and ask_user_question are excluded from them, but you can still call them directly. searchTools() and describeTool() answer the exact name of an active model-only tool with a hint to call it directly, not from a script.\nWith several text items, each starts with a ==> text N/M <== line. Console calls follow the other output in one <console_output> block, with one line per call.\nimage() also saves each image to a temp file and the result names its path before the image.\nSuccessful scripts persist store writes on the current session branch; failed scripts discard writes. Unawaited calls are cancelled when the script ends.\nOptional first line: // @options: {\"max_output_tokens\": 1000, \"timeout_ms\": 60000}. Output defaults to 10000 tokens; there is no default deadline.`;\n\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ namespace?: ToolNamespace; entries: { name: string; section: string; cost: number }[] }\n\t>();\n\tfor (const tool of getCodemodeCallableTools(tools)) {\n\t\tif (options.deferred?.has(tool.name)) continue;\n\t\tconst namespace = options.namespaces?.get(tool.name);\n\t\tconst key = namespace?.name ?? \"\";\n\t\tlet group = groups.get(key);\n\t\tif (!group) {\n\t\t\tgroup = { namespace, entries: [] };\n\t\t\tgroups.set(key, group);\n\t\t}\n\t\tconst id = toCodemodeIdentifier(tool.name);\n\t\tconst section = `### \\`${id}\\`${id === tool.name ? \"\" : ` (\\`${tool.name}\\`)`}\\n${renderToolSample(toCodemodeDeclaration(tool, options.guidelines?.get(tool.name))).trim()}`;\n\t\tgroup.entries.push({\n\t\t\tname: tool.name,\n\t\t\tsection,\n\t\t\tcost: Math.ceil(section.length / 4),\n\t\t});\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = new Set<string>();\n\tlet remaining = options.inlineBudget ?? Number.POSITIVE_INFINITY;\n\tlet queues = ordered\n\t\t.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost))\n\t\t.filter((queue) => queue.length);\n\twhile (queues.length)\n\t\tqueues = queues.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\tconst sections = [\n\t\tINTRO,\n\t\t\"Some nested tools may be omitted, including deferred tools. They remain available through tools and ALL_TOOLS. Use await searchTools(query), await describeTool(name), or await describeNamespace(name) to discover them.\",\n\t];\n\tif (options.models)\n\t\tsections.push(\n\t\t\t`Model API: \\`models\\` lists and runs classifier and image models with the session's credentials. Read ${CODEMODE_DOCS_PATH} before using it.`,\n\t\t);\n\tif (ordered.length === 0) return sections.join(\"\\n\\n\");\n\tsections.push(\"Nested tools:\");\n\tfor (const group of ordered) {\n\t\tif (group.namespace) {\n\t\t\tconst visible = group.entries.filter((entry) => shown.has(entry.name));\n\t\t\tconst listing =\n\t\t\t\tvisible.length === group.entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = group.namespace.description?.trim();\n\t\t\tsections.push(`## ${group.namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of group.entries) if (shown.has(entry.name)) sections.push(entry.section);\n\t}\n\treturn sections.join(\"\\n\\n\");\n}\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\nfunction describeScriptCall(tool: AgentTool): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\nfunction prepareLoadout(loadout: ToolLoadout, options: CodemodeToolOptions) {\n\tconst only = options.getMode?.() === \"only\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst descriptions: Record<string, string> = {};\n\tif (!only)\n\t\tfor (const tool of loadout.declared)\n\t\t\tif (callable.some((candidate) => candidate.name === tool.name))\n\t\t\t\tdescriptions[tool.name] = describeScriptCall(tool);\n\tconst listed = only ? callable : callable.filter((tool) => loadout.getExposure(tool.name) !== \"direct\");\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tconst guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)] as const));\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models,\n\t\tnamespaces,\n\t\tguidelines,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations: only\n\t\t\t? callable.filter((tool) => loadout.getExposure(tool.name) === \"direct\").map((tool) => tool.name)\n\t\t\t: [],\n\t};\n}\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\tdescription: createCodemodeDescription([], options),\n\t\tparameters: codemodeSchema,\n\t\texposure: \"model-only\",\n\t\tconcurrency: \"exclusive\",\n\t\tdefaultActive: false,\n\t\tpromptSnippet: \"Run JavaScript that calls other tools, filters results, or batches independent calls\",\n\t\tprepareLoadout: (loadout) => prepareLoadout(loadout, options),\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\texecute: async (id, input, signal, update, ctx) =>\n\t\t\t(await import(\"./execute.js\")).executeCodemode(id, input, signal, update, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\nexport function createCodemodeTool(\n\ttools: readonly AgentTool[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\treturn {\n\t\t...wrapToolDefinition(createCodemodeToolDefinition(options)),\n\t\tdescription: createCodemodeDescription(tools, options),\n\t};\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAEpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAC7C,MAAM,CAAC,MAAM,kBAAkB,GAAG,IAAI,CAAC,WAAW,EAAE,EAAE,aAAa,CAAC,CAAC;AACrE,MAAM,CAAC,MAAM,yBAAyB,GAAG,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AAQ,EAAE,EAAE,WAAW,EAAE,uBAAuB,EAAE,EAAE;QAC5F,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,CACjD,CAAC,MAAM,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,eAAe,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC;QACxF,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AACD,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAAyB,EAAE,EAChC,OAAO,GAAwB,EAAE;IAEjC,OAAO;QACN,GAAG,kBAAkB,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC;QAC5D,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,OAAO,CAAC;KACtD,CAAC;AACH,CAAC","sourcesContent":["import { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.js\";\nimport type { ToolDefinition, ToolInfo, ToolLoadout, ToolNamespace } from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport { SETTINGS_DEFAULTS } from \"../../core/settings-defaults.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { codemodeRenderers } from \"./renderer.js\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\nexport const DEFAULT_CODEMODE_INLINE_BUDGET: number = SETTINGS_DEFAULTS.codemode.inlineBudget;\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\nexport interface CodemodeToolOptions {\n\tgetToolNamespace?: (name: string) => ToolNamespace | undefined;\n\t/** Prompt guidelines shown with tool declarations in describeTool() and ALL_TOOLS. */\n\tgetToolGuidelines?: () => ReadonlyMap<string, readonly string[]>;\n\tmodels?: boolean;\n\tappendEntry?: (type: string, data: CodemodeStoreEntryData) => void;\n\tgetMode?: () => CodemodeMode;\n\tgetInlineBudget?: () => number | undefined;\n\t/** Active model-only tools. Scripts cannot call them, so discovery answers an exact name with a hint. */\n\tgetModelOnlyTools?: () => readonly string[];\n}\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription:\n\t\t\t'Raw JavaScript source with top-level await and return. Optional first line // @options: {\"max_output_tokens\": 1000, \"timeout_ms\": 60000}',\n\t}),\n});\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\nexport interface CodemodeNestedCall {\n\tid: string;\n\tname: string;\n\targs: string;\n\tstatus: \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\tdurationMs?: number;\n\terror?: string;\n\tcost?: number;\n}\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\tfullOutputPath?: string;\n}\nexport function toCodemodeDeclaration(\n\ttool: AgentTool,\n\tguidelines: readonly string[] = [],\n): Omit<CodemodeTool, \"execute\"> {\n\tconst bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: bullets.length > 0 ? `${tool.description.trim()}\\n\\n${bullets.join(\"\\n\")}` : tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? { type: \"string\" },\n\t};\n}\nexport function getCodemodeCallableTools(tools: readonly AgentTool[]): AgentTool[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\nexport interface CodemodeDescriptionOptions {\n\tmodels?: boolean;\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\tdeferred?: ReadonlySet<string>;\n\tguidelines?: ReadonlyMap<string, readonly string[]>;\n\tinlineBudget?: number;\n}\nconst INTRO = `Run JavaScript that composes tool calls in a fresh QuickJS worker sandbox.\nTop-level await and return work. Use tools.name(args), or tools[\"raw-name\"](args). Tool names normalize to JavaScript identifiers.\nNo Node, filesystem, network, timers, modules or credentials are available directly. Calls go through session validation and permission hooks. They have real side effects and are not undone after script failure.\nTools with output schemas resolve to structuredContent; others resolve to text. Failed or blocked calls throw, except that a tool with an output schema resolves with its structuredContent on failure too when it returned one; check its fields. Scripts have a 256 MB memory limit.\nGlobals: ALL_TOOLS, text(value), image(base64DataUrlOrImageContent), exit(), console.log(...), store(key, value), load(key), await searchTools(query, {limit?, namespace?}), await describeTool(name), await describeNamespace(name).\ntools, ALL_TOOLS and searchTools() matches cover only script-callable tools. Model-only tools such as subagent, workflow, intercom, and ask_user_question are excluded from them, but you can still call them directly. searchTools() and describeTool() answer the exact name of an active model-only tool with a hint to call it directly, not from a script.\nWith several text items, each starts with a ==> text N/M <== line. Console calls follow the other output in one <console_output> block, with one line per call.\nimage() also saves each image to a temp file and the result names its path before the image.\nSuccessful scripts persist store writes on the current session branch; failed scripts discard writes. Unawaited calls are cancelled when the script ends.\nOptional first line: // @options: {\"max_output_tokens\": 1000, \"timeout_ms\": 60000}. Output defaults to 10000 tokens; there is no default deadline.`;\n\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ namespace?: ToolNamespace; entries: { name: string; section: string; cost: number }[] }\n\t>();\n\tfor (const tool of getCodemodeCallableTools(tools)) {\n\t\tif (options.deferred?.has(tool.name)) continue;\n\t\tconst namespace = options.namespaces?.get(tool.name);\n\t\tconst key = namespace?.name ?? \"\";\n\t\tlet group = groups.get(key);\n\t\tif (!group) {\n\t\t\tgroup = { namespace, entries: [] };\n\t\t\tgroups.set(key, group);\n\t\t}\n\t\tconst id = toCodemodeIdentifier(tool.name);\n\t\tconst section = `### \\`${id}\\`${id === tool.name ? \"\" : ` (\\`${tool.name}\\`)`}\\n${renderToolSample(toCodemodeDeclaration(tool, options.guidelines?.get(tool.name))).trim()}`;\n\t\tgroup.entries.push({\n\t\t\tname: tool.name,\n\t\t\tsection,\n\t\t\tcost: Math.ceil(section.length / 4),\n\t\t});\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = new Set<string>();\n\tlet remaining = options.inlineBudget ?? Number.POSITIVE_INFINITY;\n\tlet queues = ordered\n\t\t.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost))\n\t\t.filter((queue) => queue.length);\n\twhile (queues.length)\n\t\tqueues = queues.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\tconst sections = [\n\t\tINTRO,\n\t\t\"Some nested tools may be omitted, including deferred tools. They remain available through tools and ALL_TOOLS. Use await searchTools(query), await describeTool(name), or await describeNamespace(name) to discover them.\",\n\t];\n\tif (options.models)\n\t\tsections.push(\n\t\t\t`Model API: \\`models\\` lists and runs classifier and image models with the session's credentials. Read ${CODEMODE_DOCS_PATH} before using it.`,\n\t\t);\n\tif (ordered.length === 0) return sections.join(\"\\n\\n\");\n\tsections.push(\"Nested tools:\");\n\tfor (const group of ordered) {\n\t\tif (group.namespace) {\n\t\t\tconst visible = group.entries.filter((entry) => shown.has(entry.name));\n\t\t\tconst listing =\n\t\t\t\tvisible.length === group.entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = group.namespace.description?.trim();\n\t\t\tsections.push(`## ${group.namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of group.entries) if (shown.has(entry.name)) sections.push(entry.section);\n\t}\n\treturn sections.join(\"\\n\\n\");\n}\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\nfunction describeScriptCall(tool: AgentTool): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\nfunction prepareLoadout(loadout: ToolLoadout, options: CodemodeToolOptions) {\n\tconst only = options.getMode?.() === \"only\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst descriptions: Record<string, string> = {};\n\tif (!only)\n\t\tfor (const tool of loadout.declared)\n\t\t\tif (callable.some((candidate) => candidate.name === tool.name))\n\t\t\t\tdescriptions[tool.name] = describeScriptCall(tool);\n\tconst listed = only ? callable : callable.filter((tool) => loadout.getExposure(tool.name) !== \"direct\");\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tconst guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)] as const));\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models,\n\t\tnamespaces,\n\t\tguidelines,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations: only\n\t\t\t? callable.filter((tool) => loadout.getExposure(tool.name) === \"direct\").map((tool) => tool.name)\n\t\t\t: [],\n\t};\n}\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\tdescription: createCodemodeDescription([], options),\n\t\tparameters: codemodeSchema,\n\t\texposure: \"model-only\",\n\t\tconcurrency: \"exclusive\",\n\t\tdefaultActive: false,\n\t\tpromptSnippet: \"Run JavaScript that calls other tools, filters results, or batches independent calls\",\n\t\tprepareLoadout: (loadout) => prepareLoadout(loadout, options),\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\texecute: async (id, input, signal, update, ctx) =>\n\t\t\t(await import(\"./execute.js\")).executeCodemode(id, input, signal, update, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\nexport function createCodemodeTool(\n\ttools: readonly AgentTool[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\treturn {\n\t\t...wrapToolDefinition(createCodemodeToolDefinition(options)),\n\t\tdescription: createCodemodeDescription(tools, options),\n\t};\n}\n"]}
@@ -4,10 +4,11 @@ export declare class OAuthError extends Error {
4
4
  constructor(code: string, message: string, errorUri?: string);
5
5
  }
6
6
  export declare class OAuthIssuerMismatchError extends Error {
7
- readonly expected: string;
7
+ /** `undefined` when no authorization server metadata was discovered. */
8
+ readonly expected: string | undefined;
8
9
  /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
9
10
  readonly received: string | undefined;
10
- constructor(expected: string, received: string | undefined);
11
+ constructor(expected: string | undefined, received: string | undefined);
11
12
  }
12
13
  export declare class OAuthInsecureEndpointError extends Error {
13
14
  readonly endpoint: string;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../../src/extensions/mcp/client/oauth/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAW,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAK3D;CACD;AAED,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,2GAA2G;IAC3G,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAOzD;CACD;AAED,qBAAa,0BAA2B,SAAQ,KAAK;IACpD,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BAAa,kCAAmC,SAAQ,KAAK;IAC5D,cAGC;CACD"}
@@ -9,11 +9,13 @@ export class OAuthError extends Error {
9
9
  }
10
10
  }
11
11
  export class OAuthIssuerMismatchError extends Error {
12
+ /** `undefined` when no authorization server metadata was discovered. */
12
13
  expected;
13
14
  /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
14
15
  received;
15
16
  constructor(expected, received) {
16
- super(`OAuth issuer mismatch: expected ${JSON.stringify(expected)}, received ${received === undefined ? "none" : JSON.stringify(received)}`);
17
+ const format = (issuer) => (issuer === undefined ? "none" : JSON.stringify(issuer));
18
+ super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);
17
19
  this.name = "OAuthIssuerMismatchError";
18
20
  this.expected = expected;
19
21
  this.received = received;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/extensions/mcp/client/oauth/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC3B,IAAI,CAAS;IACb,QAAQ,CAAqB;IAEtC,YAAY,IAAY,EAAE,OAAe,EAAE,QAAiB;QAC3D,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IACzC,QAAQ,CAAS;IAC1B,2GAA2G;IAClG,QAAQ,CAAqB;IAEtC,YAAY,QAAgB,EAAE,QAA4B;QACzD,KAAK,CACJ,mCAAmC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,cAAc,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CACrI,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IAC3C,QAAQ,CAAS;IAE1B,YAAY,QAAgB;QAC3B,KAAK,CAAC,4DAA4D,QAAQ,EAAE,CAAC,CAAC;QAC9E,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IACvC,MAAM,CAAS;IACf,IAAI,CAAS;IAEtB,YAAY,MAAc,EAAE,IAAY;QACvC,KAAK,CAAC,wDAAwD,MAAM,KAAK,IAAI,EAAE,CAAC,CAAC;QACjF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAC5D;QACC,KAAK,CAAC,mDAAmD,CAAC,CAAC;QAC3D,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IAClD,CAAC;CACD","sourcesContent":["export class OAuthError extends Error {\n\treadonly code: string;\n\treadonly errorUri: string | undefined;\n\n\tconstructor(code: string, message: string, errorUri?: string) {\n\t\tsuper(message || code);\n\t\tthis.name = \"OAuthError\";\n\t\tthis.code = code;\n\t\tthis.errorUri = errorUri;\n\t}\n}\n\nexport class OAuthIssuerMismatchError extends Error {\n\treadonly expected: string;\n\t/** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */\n\treadonly received: string | undefined;\n\n\tconstructor(expected: string, received: string | undefined) {\n\t\tsuper(\n\t\t\t`OAuth issuer mismatch: expected ${JSON.stringify(expected)}, received ${received === undefined ? \"none\" : JSON.stringify(received)}`,\n\t\t);\n\t\tthis.name = \"OAuthIssuerMismatchError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n\nexport class OAuthInsecureEndpointError extends Error {\n\treadonly endpoint: string;\n\n\tconstructor(endpoint: string) {\n\t\tsuper(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);\n\t\tthis.name = \"OAuthInsecureEndpointError\";\n\t\tthis.endpoint = endpoint;\n\t}\n}\n\nexport class OAuthRegistrationError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, body: string) {\n\t\tsuper(`OAuth dynamic client registration failed with status ${status}: ${body}`);\n\t\tthis.name = \"OAuthRegistrationError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpOAuthAuthorizationRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(\"MCP OAuth authorization requires user interaction\");\n\t\tthis.name = \"McpOAuthAuthorizationRequiredError\";\n\t}\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../../src/extensions/mcp/client/oauth/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC3B,IAAI,CAAS;IACb,QAAQ,CAAqB;IAEtC,YAAY,IAAY,EAAE,OAAe,EAAE,QAAiB;QAC3D,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAClD,wEAAwE;IAC/D,QAAQ,CAAqB;IACtC,2GAA2G;IAClG,QAAQ,CAAqB;IAEtC,YAAY,QAA4B,EAAE,QAA4B;QACrE,MAAM,MAAM,GAAG,CAAC,MAA0B,EAAE,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;QACxG,KAAK,CAAC,mCAAmC,MAAM,CAAC,QAAQ,CAAC,cAAc,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC3F,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IAC3C,QAAQ,CAAS;IAE1B,YAAY,QAAgB;QAC3B,KAAK,CAAC,4DAA4D,QAAQ,EAAE,CAAC,CAAC;QAC9E,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IACvC,MAAM,CAAS;IACf,IAAI,CAAS;IAEtB,YAAY,MAAc,EAAE,IAAY;QACvC,KAAK,CAAC,wDAAwD,MAAM,KAAK,IAAI,EAAE,CAAC,CAAC;QACjF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAC5D;QACC,KAAK,CAAC,mDAAmD,CAAC,CAAC;QAC3D,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IAClD,CAAC;CACD","sourcesContent":["export class OAuthError extends Error {\n\treadonly code: string;\n\treadonly errorUri: string | undefined;\n\n\tconstructor(code: string, message: string, errorUri?: string) {\n\t\tsuper(message || code);\n\t\tthis.name = \"OAuthError\";\n\t\tthis.code = code;\n\t\tthis.errorUri = errorUri;\n\t}\n}\n\nexport class OAuthIssuerMismatchError extends Error {\n\t/** `undefined` when no authorization server metadata was discovered. */\n\treadonly expected: string | undefined;\n\t/** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */\n\treadonly received: string | undefined;\n\n\tconstructor(expected: string | undefined, received: string | undefined) {\n\t\tconst format = (issuer: string | undefined) => (issuer === undefined ? \"none\" : JSON.stringify(issuer));\n\t\tsuper(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);\n\t\tthis.name = \"OAuthIssuerMismatchError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n\nexport class OAuthInsecureEndpointError extends Error {\n\treadonly endpoint: string;\n\n\tconstructor(endpoint: string) {\n\t\tsuper(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);\n\t\tthis.name = \"OAuthInsecureEndpointError\";\n\t\tthis.endpoint = endpoint;\n\t}\n}\n\nexport class OAuthRegistrationError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, body: string) {\n\t\tsuper(`OAuth dynamic client registration failed with status ${status}: ${body}`);\n\t\tthis.name = \"OAuthRegistrationError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpOAuthAuthorizationRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(\"MCP OAuth authorization requires user interaction\");\n\t\tthis.name = \"McpOAuthAuthorizationRequiredError\";\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"flow.d.ts","sourceRoot":"","sources":["../../../../../src/extensions/mcp/client/oauth/flow.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAuB,MAAM,qBAAqB,CAAC;AAevF,OAAO,EACN,KAAK,2BAA2B,EAEhC,KAAK,0BAA0B,EAC/B,KAAK,2BAA2B,EAChC,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,WAAW,EAGhB,MAAM,YAAY,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EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAC9F,OAAO,CAAC,WAAW,CAAC,CAWtB;AAED,wBAAsB,oBAAoB,CACzC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,OAAO,EAAE,mBAAmB,GAAG;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,GACrD,OAAO,CAAC,WAAW,CAAC,CAOtB;AAMD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAI3G;AAmHD,wBAAsB,YAAY,CAAC,QAAQ,EAAE,mBAAmB,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CAcrH;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,YAAY,CA8B9E"}
@@ -228,11 +228,12 @@ async function runFlow(provider, options) {
228
228
  signal: options.signal,
229
229
  };
230
230
  if (options.authorizationCode) {
231
- // RFC 9207: never send a code from another authorization server to this one.
231
+ // RFC 9207: never send a code from another authorization server to this one. Without metadata there
232
+ // is no issuer to compare with, so any `iss` is rejected.
232
233
  const iss = options.iss;
233
- if (metadata && (iss !== undefined || metadata.authorization_response_iss_parameter_supported)) {
234
- if (iss !== metadata.issuer)
235
- throw new OAuthIssuerMismatchError(metadata.issuer, iss);
234
+ if (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {
235
+ if (iss !== metadata?.issuer)
236
+ throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
236
237
  }
237
238
  const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
238
239
  ...tokenOptions,