@bastani/atomic 0.9.20-alpha.9 → 0.9.21-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.
- package/CHANGELOG.md +253 -0
- package/dist/builtin/intercom/CHANGELOG.md +25 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/CHANGELOG.md +13 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +50 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/tdd/SKILL.md +10 -2
- package/dist/builtin/subagents/skills/tdd/mocking.md +4 -0
- package/dist/builtin/subagents/skills/tdd/test-audit.md +105 -0
- package/dist/builtin/subagents/skills/tdd/tests.md +3 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +2 -1
- package/dist/builtin/web-access/CHANGELOG.md +13 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +144 -0
- package/dist/builtin/workflows/README.md +1 -1
- package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
- package/dist/builtin/workflows/builtin/{chunk-7ps7bnb4.js → chunk-0nrgfbag.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-2npg6daz.js → chunk-2hak3b7g.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-twefqrv0.js → chunk-73c5tayt.js} +36 -3
- package/dist/builtin/workflows/builtin/{chunk-18yz7r43.js → chunk-bzdvx2xr.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-24c235x7.js → chunk-crw7q5g1.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-f8jjd90r.js → chunk-cw86srkf.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-z5xdqrs6.js → chunk-jaj27rqc.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-gxrhbnaj.js → chunk-kspvwc24.js} +2 -2
- package/dist/builtin/workflows/builtin/{chunk-ynded223.js → chunk-maqv731g.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-1pd5zcfa.js → chunk-vkmpdat4.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-2jv44yz7.js → chunk-w18kbz63.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-ad864596.js → chunk-wh19f5ee.js} +3 -3
- package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
- package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
- package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
- package/dist/builtin/workflows/builtin/goal.js +4 -4
- package/dist/builtin/workflows/builtin/index.js +12 -12
- package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
- package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +4 -4
- package/dist/builtin/workflows/builtin/steering-context.js +1 -1
- package/dist/builtin/workflows/builtin/tournament.js +3 -3
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +107 -34
- package/dist/builtin/workflows/src/index.js +93 -27
- package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
- package/dist/core/agent-session-queue-pause.js +2 -1
- package/dist/core/agent-session-queue-pause.js.map +1 -1
- package/dist/core/context-tool-pairing.d.ts +10 -14
- package/dist/core/context-tool-pairing.d.ts.map +1 -1
- package/dist/core/context-tool-pairing.js +99 -28
- package/dist/core/context-tool-pairing.js.map +1 -1
- package/dist/core/execution-model-router.d.ts.map +1 -1
- package/dist/core/execution-model-router.js +21 -11
- package/dist/core/execution-model-router.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +2 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-routing-task.d.ts +6 -1
- package/dist/core/model-routing-task.d.ts.map +1 -1
- package/dist/core/model-routing-task.js +56 -13
- package/dist/core/model-routing-task.js.map +1 -1
- package/dist/core/structured-output/index.d.ts.map +1 -1
- package/dist/core/structured-output/index.js +7 -4
- package/dist/core/structured-output/index.js.map +1 -1
- package/dist/core/system-prompt.js +2 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/docs/computer-use.md +31 -7
- package/docs/getting-started/first-session.md +1 -1
- package/docs/models/model-selection.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/subagents/reference.md +1 -1
- package/docs/usage.md +1 -1
- package/docs/workflows/authoring.md +15 -1
- package/docs/workflows/operations.md +3 -1
- package/docs/workflows/reliable-design.md +3 -1
- package/docs/workflows/verification.md +25 -7
- package/docs/workflows.md +1 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -30315,43 +30315,76 @@ async function connectLockClient(url) {
|
|
|
30315
30315
|
end: async () => await client.end()
|
|
30316
30316
|
};
|
|
30317
30317
|
}
|
|
30318
|
-
|
|
30319
|
-
|
|
30318
|
+
function isLaunchLockConnectionError(error) {
|
|
30319
|
+
if (!(error instanceof Error))
|
|
30320
|
+
return false;
|
|
30321
|
+
const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
|
|
30322
|
+
if (code !== undefined && (CONNECTION_ERROR_CODES.has(code) || /^08|^57P0[123]$/u.test(code)))
|
|
30323
|
+
return true;
|
|
30324
|
+
return /connection terminated|connection refused|server closed the connection/iu.test(error.message);
|
|
30325
|
+
}
|
|
30326
|
+
async function closeQuietly(client) {
|
|
30327
|
+
await client.end().catch(() => {
|
|
30328
|
+
return;
|
|
30329
|
+
});
|
|
30330
|
+
}
|
|
30331
|
+
async function acquire(url, options) {
|
|
30332
|
+
const connect = options.connect ?? connectLockClient;
|
|
30333
|
+
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
30334
|
+
const maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
|
|
30335
|
+
const connectRetries = options.connectRetries ?? DEFAULT_CONNECT_RETRIES;
|
|
30336
|
+
const started = performance.now();
|
|
30337
|
+
const deadline = started + maxWaitMs;
|
|
30338
|
+
let connectFailures = 0;
|
|
30339
|
+
let retryDelayMs = options.connectRetryDelayMs ?? DEFAULT_CONNECT_RETRY_DELAY_MS;
|
|
30320
30340
|
for (;; ) {
|
|
30321
|
-
|
|
30322
|
-
|
|
30323
|
-
|
|
30324
|
-
|
|
30325
|
-
|
|
30326
|
-
|
|
30341
|
+
let client;
|
|
30342
|
+
try {
|
|
30343
|
+
client = await connect(url);
|
|
30344
|
+
for (;; ) {
|
|
30345
|
+
const result = await client.query("SELECT pg_try_advisory_lock($1::bigint) AS locked", [
|
|
30346
|
+
DBOS_LAUNCH_LOCK_KEY
|
|
30347
|
+
]);
|
|
30348
|
+
if (result.rows[0]?.locked === true)
|
|
30349
|
+
return client;
|
|
30350
|
+
if (performance.now() >= deadline)
|
|
30351
|
+
throw new DbosLaunchLockTimeoutError(performance.now() - started);
|
|
30352
|
+
await sleep(pollIntervalMs);
|
|
30353
|
+
}
|
|
30354
|
+
} catch (error) {
|
|
30355
|
+
if (client !== undefined)
|
|
30356
|
+
await closeQuietly(client);
|
|
30357
|
+
if (!isLaunchLockConnectionError(error))
|
|
30358
|
+
throw error;
|
|
30359
|
+
connectFailures += 1;
|
|
30360
|
+
if (connectFailures > connectRetries || performance.now() + retryDelayMs >= deadline)
|
|
30361
|
+
throw error;
|
|
30362
|
+
await sleep(retryDelayMs);
|
|
30363
|
+
retryDelayMs = Math.min(retryDelayMs * 2, MAX_CONNECT_RETRY_DELAY_MS);
|
|
30364
|
+
}
|
|
30327
30365
|
}
|
|
30328
30366
|
}
|
|
30329
30367
|
async function withDbosLaunchLock(url, launch, options = {}) {
|
|
30330
|
-
const
|
|
30331
|
-
let client;
|
|
30332
|
-
try {
|
|
30333
|
-
client = await connect(url);
|
|
30334
|
-
} catch {
|
|
30335
|
-
return await launch();
|
|
30336
|
-
}
|
|
30337
|
-
let locked = false;
|
|
30368
|
+
const client = await acquire(url, options);
|
|
30338
30369
|
try {
|
|
30339
|
-
locked = await acquire(client, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS).catch(() => false);
|
|
30340
30370
|
return await launch();
|
|
30341
30371
|
} finally {
|
|
30342
|
-
|
|
30343
|
-
await client.query("SELECT pg_advisory_unlock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]).catch(() => {
|
|
30344
|
-
return;
|
|
30345
|
-
});
|
|
30346
|
-
}
|
|
30347
|
-
await client.end().catch(() => {
|
|
30372
|
+
await client.query("SELECT pg_advisory_unlock($1::bigint) AS locked", [DBOS_LAUNCH_LOCK_KEY]).catch(() => {
|
|
30348
30373
|
return;
|
|
30349
30374
|
});
|
|
30375
|
+
await closeQuietly(client);
|
|
30350
30376
|
}
|
|
30351
30377
|
}
|
|
30352
|
-
var DBOS_LAUNCH_LOCK_KEY = "4702111234474983745", LOCK_CONNECT_TIMEOUT_MS = 1e4, DEFAULT_POLL_INTERVAL_MS = 100, DEFAULT_MAX_WAIT_MS = 60000;
|
|
30378
|
+
var DBOS_LAUNCH_LOCK_KEY = "4702111234474983745", LOCK_CONNECT_TIMEOUT_MS = 1e4, DEFAULT_POLL_INTERVAL_MS = 100, DEFAULT_MAX_WAIT_MS = 60000, DEFAULT_CONNECT_RETRIES = 3, DEFAULT_CONNECT_RETRY_DELAY_MS = 250, MAX_CONNECT_RETRY_DELAY_MS = 2000, CONNECTION_ERROR_CODES, DbosLaunchLockTimeoutError, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
30353
30379
|
var init_dbos_launch_lock = __esm(() => {
|
|
30354
30380
|
init_esm();
|
|
30381
|
+
CONNECTION_ERROR_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EPIPE", "ENOTFOUND", "EAI_AGAIN"]);
|
|
30382
|
+
DbosLaunchLockTimeoutError = class DbosLaunchLockTimeoutError extends Error {
|
|
30383
|
+
constructor(waitedMs) {
|
|
30384
|
+
super(`Timed out after ${Math.round(waitedMs / 1000)}s waiting for the DBOS launch lock; another process is still launching DBOS against this database. DBOS was not launched.`);
|
|
30385
|
+
this.name = "DbosLaunchLockTimeoutError";
|
|
30386
|
+
}
|
|
30387
|
+
};
|
|
30355
30388
|
});
|
|
30356
30389
|
|
|
30357
30390
|
// dist/builtin/workflows/src/durable/dbos-managed-health.ts
|
|
@@ -39742,7 +39775,7 @@ import {
|
|
|
39742
39775
|
rm,
|
|
39743
39776
|
writeFile
|
|
39744
39777
|
} from "node:fs/promises";
|
|
39745
|
-
import { homedir } from "node:os";
|
|
39778
|
+
import { homedir, userInfo } from "node:os";
|
|
39746
39779
|
import { basename as basename2, dirname, isAbsolute, join, normalize, relative, sep } from "node:path";
|
|
39747
39780
|
|
|
39748
39781
|
// dist/builtin/workflows/src/durable/local-command.ts
|
|
@@ -40101,7 +40134,37 @@ async function findOrCreateRuntimeGeneration(binaries, sourceNativeDir, sourceSn
|
|
|
40101
40134
|
await rm(stagedRoot, { recursive: true, force: true });
|
|
40102
40135
|
}
|
|
40103
40136
|
}
|
|
40104
|
-
|
|
40137
|
+
var SYSTEM_ACCOUNT_FILES = { group: "/etc/group", passwd: "/etc/passwd" };
|
|
40138
|
+
async function readAccountRecords(path, gidField) {
|
|
40139
|
+
try {
|
|
40140
|
+
return (await readFile(path, "utf8")).split(/\r?\n/u).map((line) => line.split(":")).filter((fields) => fields.length > gidField && /^\d+$/u.test(fields[gidField]));
|
|
40141
|
+
} catch {
|
|
40142
|
+
return;
|
|
40143
|
+
}
|
|
40144
|
+
}
|
|
40145
|
+
async function isUserPrivateGroup(gid, account, files = SYSTEM_ACCOUNT_FILES) {
|
|
40146
|
+
const groups = await readAccountRecords(files.group, 2);
|
|
40147
|
+
const users = await readAccountRecords(files.passwd, 3);
|
|
40148
|
+
if (groups === undefined || users === undefined)
|
|
40149
|
+
return false;
|
|
40150
|
+
const entries = groups.filter((fields) => Number(fields[2]) === gid);
|
|
40151
|
+
if (entries.length === 0)
|
|
40152
|
+
return false;
|
|
40153
|
+
const primaryMembers = users.filter((fields) => Number(fields[3]) === gid);
|
|
40154
|
+
if (primaryMembers.some((fields) => !/^\d+$/u.test(fields[2]) || Number(fields[2]) !== account.uid))
|
|
40155
|
+
return false;
|
|
40156
|
+
const supplementaryMembers = entries.flatMap((fields) => (fields[3] ?? "").split(",").map((member) => member.trim()).filter((member) => member !== ""));
|
|
40157
|
+
if (supplementaryMembers.some((member) => member !== account.username))
|
|
40158
|
+
return false;
|
|
40159
|
+
return primaryMembers.length + supplementaryMembers.length > 0;
|
|
40160
|
+
}
|
|
40161
|
+
function publisherAccount(publisher) {
|
|
40162
|
+
return {
|
|
40163
|
+
uid: publisher.uid,
|
|
40164
|
+
username: process.getuid?.() === publisher.uid ? userInfo().username : undefined
|
|
40165
|
+
};
|
|
40166
|
+
}
|
|
40167
|
+
async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity(), needsPrivilegeDrop = false, owner, inspect = lstat, privateGroup = (gid) => isUserPrivateGroup(gid, publisherAccount(publisher))) {
|
|
40105
40168
|
if (!isAbsolute(path))
|
|
40106
40169
|
throw new Error(`Embedded Postgres runtime cache override must be absolute: ${path}`);
|
|
40107
40170
|
await mkdir(path, { recursive: true, mode: 493 });
|
|
@@ -40111,7 +40174,10 @@ async function ensureRuntimeCacheDirectory(path, publisher = publisherIdentity()
|
|
|
40111
40174
|
let ancestor = await realpath(path);
|
|
40112
40175
|
while (true) {
|
|
40113
40176
|
const info = await inspect(ancestor);
|
|
40114
|
-
|
|
40177
|
+
const sticky = (info.mode & 512) !== 0;
|
|
40178
|
+
const writableByOthers = !sticky && (info.mode & 2) !== 0;
|
|
40179
|
+
const writableByGroup = !sticky && (info.mode & 16) !== 0;
|
|
40180
|
+
if (!info.isDirectory() || process.platform !== "win32" && (info.uid !== 0 && info.uid !== publisher.uid || writableByOthers || writableByGroup && (info.gid !== publisher.gid || !await privateGroup(info.gid))))
|
|
40115
40181
|
throw new Error(`Untrusted embedded Postgres runtime cache directory ancestor: ${ancestor}`);
|
|
40116
40182
|
if (needsPrivilegeDrop && owner && publisher.uid === 0 && process.platform !== "win32") {
|
|
40117
40183
|
const execute = info.uid === owner.uid ? 64 : info.gid === owner.gid ? 8 : 1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-queue-pause.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-queue-pause.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAkB9F,yFAAyF;AACzF,wBAAgB,2BAA2B,CAC1C,UAAU,EAAE,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,EAAE,GAChD,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAG3B;AAED,uFAAuF;AACvF,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAU5D;AAED,0FAA0F;AAC1F,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,YAAY,EAAE,aAAa,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAgC3G;AAED,iGAAiG;AACjG,wBAAgB,KAAK,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAKvD;AAED,oFAAoF;AACpF,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"agent-session-queue-pause.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-queue-pause.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAkB9F,yFAAyF;AACzF,wBAAgB,2BAA2B,CAC1C,UAAU,EAAE,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,EAAE,GAChD,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAG3B;AAED,uFAAuF;AACvF,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAU5D;AAED,0FAA0F;AAC1F,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,YAAY,EAAE,aAAa,CAAC,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAgC3G;AAED,iGAAiG;AACjG,wBAAgB,KAAK,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAKvD;AAED,oFAAoF;AACpF,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAuCxE"}
|
|
@@ -90,7 +90,8 @@ export function abortCurrentGeneration() {
|
|
|
90
90
|
// protocol-safe persistence is still pending so they cannot restart it.
|
|
91
91
|
this._subagentMessageAdmission.seal();
|
|
92
92
|
}
|
|
93
|
-
|
|
93
|
+
const ownsStageDeliveries = resolveWorkflowStageDeliveryTarget(this) === this;
|
|
94
|
+
if ((this._subagentMessageAdmission || this._workflowStageAdmission) && ownsStageDeliveries) {
|
|
94
95
|
// Unlike a priority interrupt's native abort, an explicit stop must also
|
|
95
96
|
// block deferred input from starting a turn after preflight or settlement.
|
|
96
97
|
// A stage's generation remains host-owned; only explicit resume releases it.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-queue-pause.js","sourceRoot":"","sources":["../../src/core/agent-session-queue-pause.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,KAAK,UAAU,0BAA0B,CAAC,UAAoC;IAC7E,IAAI,iBAA4C,CAAC;IACjD,MAAM,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;QACjC,IAAI,CAAC;YACJ,MAAM,QAAQ,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,iBAAiB,KAAK,GAAG,EAAE;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AC3C,IAAI,CAAC,iCAAiC,GAAG,OAAO,CAAC;QACjD,KAAK,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nasync function settlePauseAbortBoundaries(boundaries: readonly Promise<void>[]): Promise<void> {\n\tlet throwFirstFailure: (() => never) | undefined;\n\tawait Promise.all(\n\t\tboundaries.map(async (boundary) => {\n\t\t\ttry {\n\t\t\t\tawait boundary;\n\t\t\t} catch (error) {\n\t\t\t\tthrowFirstFailure ??= () => {\n\t\t\t\t\tthrow error;\n\t\t\t\t};\n\t\t\t}\n\t\t}),\n\t);\n\tthrowFirstFailure?.();\n}\n\n/** Compose pause settlement without exposing an early rejection from one constituent. */\nexport function composePauseAbortBoundaries(\n\tboundaries: readonly (Promise<void> | undefined)[],\n): Promise<void> | undefined {\n\tconst pending = boundaries.filter((boundary): boundary is Promise<void> => boundary !== undefined);\n\treturn pending.length === 0 ? undefined : settlePauseAbortBoundaries(pending);\n}\n\n/** Synchronously hold raw queue entries before pausing and aborting an active turn. */\nexport function pauseQueuedMessages(this: AgentSession): void {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\towner.pauseQueuedMessages();\n\t\treturn;\n\t}\n\tif (this._queuedMessagesPaused) return;\n\tthis._queuedMessagesPaused = true;\n\tthis._queuedMessagesPauseAbortBoundary = undefined;\n\tthis._ensureActiveInterruptQueueHold();\n}\n\n/** Release a pause hold without starting a turn; report whether raw work was released. */\nexport async function resumeQueuedMessages(this: AgentSession, beforeRelease?: () => void): Promise<boolean> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.resumeQueuedMessages(beforeRelease);\n\tif (!this._queuedMessagesPaused) return false;\n\tconst abortBoundary = this._queuedMessagesPauseAbortBoundary;\n\tif (abortBoundary !== undefined) {\n\t\ttry {\n\t\t\tawait abortBoundary;\n\t\t} catch (error) {\n\t\t\t// Keep the hold closed across a failed abort. The rejecting explicit\n\t\t\t// resume observes that boundary and retires it so a later resume can retry.\n\t\t\tif (this._queuedMessagesPauseAbortBoundary === abortBoundary) {\n\t\t\t\tthis._queuedMessagesPauseAbortBoundary = undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\tif (this._pendingInterruptDeliveries > 0) await this._interruptDeliveryQueue;\n\t// An admitted-message recovery turn is a session-owned turn starter that begins\n\t// after the abort boundary settles. Releasing while it streams would let the\n\t// caller's follow-on prompt hit the streaming guard (issue #2362).\n\tconst recoveryTurn = this._admittedRecoveryTurn;\n\tif (recoveryTurn !== undefined) await recoveryTurn;\n\tif (!this._queuedMessagesPaused) return false;\n\tbeforeRelease?.();\n\tconst hold = this._activeInterruptQueueHold;\n\tconst released = hold !== undefined && (hold.steering.length > 0 || hold.followUp.length > 0);\n\tthis._queuedMessagesPaused = false;\n\tthis._agentRunAbortRequested = false;\n\tthis._queuedMessagesPauseAbortBoundary = undefined;\n\tthis._restoreAndClearActiveInterruptQueueHold();\n\treturn released;\n}\n\n/** Abort an ordinary turn and synchronously publish its pause-associated settlement boundary. */\nexport function abort(this: AgentSession): Promise<void> {\n\tthis._extensionRunner.cancelHostInput();\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.abort();\n\treturn abortCurrentGeneration.call(this);\n}\n\n/** Internal teardown never redirects cancellation into a replacement generation. */\nexport function abortCurrentGeneration(this: AgentSession): Promise<void> {\n\tthis._extensionRunner.cancelHostInput();\n\tthis._agentRunAbortRequested = true;\n\tthis._cacheWarmer?.cancel();\n\tthis._postCompactionContinuationToken += 1;\n\tif (this._subagentMessageAdmission) {\n\t\t// Cancellation is terminal for a child. Hold even deliveries whose\n\t\t// protocol-safe persistence is still pending so they cannot restart it.\n\t\tthis._subagentMessageAdmission.seal();\n\t}\n\tconst ownsStageDeliveries = resolveWorkflowStageDeliveryTarget(this) === this;\n\tif ((this._subagentMessageAdmission || this._workflowStageAdmission) && ownsStageDeliveries) {\n\t\t// Unlike a priority interrupt's native abort, an explicit stop must also\n\t\t// block deferred input from starting a turn after preflight or settlement.\n\t\t// A stage's generation remains host-owned; only explicit resume releases it.\n\t\tthis.pauseQueuedMessages();\n\t}\n\tthis.abortRetry();\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n\tthis._branchSummaryAbortController?.abort();\n\tthis.agent.abort();\n\tconst manualCompaction = this._manualCompactionPromise;\n\tconst automaticCompaction = this._autoCompactionCompletion;\n\tconst branchSummary = this._branchSummaryCompletion;\n\tconst boundary = (async () => {\n\t\tawait this.agent.waitForIdle();\n\t\tawait Promise.allSettled(\n\t\t\t[manualCompaction, automaticCompaction, branchSummary].filter((value) => value !== undefined),\n\t\t);\n\t\tawait this._agentEventQueue;\n\t})();\n\tif (this._queuedMessagesPaused) {\n\t\tconst tracked = composePauseAbortBoundaries([this._queuedMessagesPauseAbortBoundary, boundary]);\n\t\tif (tracked === undefined) return boundary;\n\t\tthis._queuedMessagesPauseAbortBoundary = tracked;\n\t\tvoid tracked.catch(() => {});\n\t}\n\treturn boundary;\n}\n"]}
|
|
@@ -1,19 +1,15 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
export declare function findDuplicateToolCallIds(messages: readonly AgentMessage[]): string[];
|
|
3
|
+
/** Throw a descriptive error when context carries the same assistant turn more than once. */
|
|
4
|
+
export declare function assertToolPairingInvariant(messages: readonly AgentMessage[]): void;
|
|
2
5
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* `repairOrphanToolResults` already collapses the recoverable forms of this
|
|
6
|
-
* invariant at conversion time: orphaned or duplicate `tool_result` blocks and
|
|
7
|
-
* tool calls interrupted before their result was persisted. None need to reach
|
|
8
|
-
* the provider.
|
|
6
|
+
* Give every tool call a non-empty id that no earlier call in the context uses.
|
|
9
7
|
*
|
|
10
|
-
* A
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
8
|
+
* A reused or empty id is renamed after its assistant turn, and the tool results
|
|
9
|
+
* following that turn (up to the next assistant message) are renamed with it in
|
|
10
|
+
* call order. Renaming depends only on earlier messages, so the derived ids stay
|
|
11
|
+
* stable as the conversation grows and do not invalidate provider prompt caches.
|
|
12
|
+
* Messages that need no change are returned as the same objects.
|
|
15
13
|
*/
|
|
16
|
-
export declare function
|
|
17
|
-
/** Throw a descriptive error when context carries a tool call id more than once. */
|
|
18
|
-
export declare function assertToolPairingInvariant(messages: readonly AgentMessage[]): void;
|
|
14
|
+
export declare function uniquifyToolCallIds<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[];
|
|
19
15
|
//# sourceMappingURL=context-tool-pairing.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-tool-pairing.d.ts","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"context-tool-pairing.d.ts","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAqDlE,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,EAAE,CAiBpF;AAED,6FAA6F;AAC7F,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,IAAI,CASlF;AAoBD;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,SAAS,YAAY,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,QAAQ,EAAE,CAkCnG"}
|
|
@@ -1,43 +1,48 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
function isToolCallBlock(block) {
|
|
2
|
+
if (!block || typeof block !== "object")
|
|
3
|
+
return false;
|
|
4
|
+
const candidate = block;
|
|
5
|
+
return candidate.type === "toolCall" && typeof candidate.id === "string";
|
|
6
|
+
}
|
|
7
|
+
function toolCallBlocks(message) {
|
|
8
|
+
const content = message.content;
|
|
9
|
+
return Array.isArray(content) ? content.filter(isToolCallBlock) : [];
|
|
10
|
+
}
|
|
11
|
+
function responseId(message) {
|
|
12
|
+
const id = message.responseId;
|
|
13
|
+
return typeof id === "string" && id !== "" ? id : undefined;
|
|
14
|
+
}
|
|
15
|
+
function isSameAssistantTurn(first, second) {
|
|
16
|
+
if (first === second)
|
|
17
|
+
return true;
|
|
18
|
+
const firstResponse = responseId(first);
|
|
19
|
+
const secondResponse = responseId(second);
|
|
20
|
+
if (firstResponse !== undefined && secondResponse !== undefined)
|
|
21
|
+
return firstResponse === secondResponse;
|
|
22
|
+
return first.timestamp === second.timestamp && JSON.stringify(first) === JSON.stringify(second);
|
|
23
|
+
}
|
|
15
24
|
export function findDuplicateToolCallIds(messages) {
|
|
16
|
-
const
|
|
25
|
+
const announcers = new Map();
|
|
17
26
|
const duplicates = new Set();
|
|
18
27
|
for (const message of messages) {
|
|
19
28
|
if (message.role !== "assistant")
|
|
20
29
|
continue;
|
|
21
30
|
if (message.excludeFromContext === true)
|
|
22
31
|
continue;
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
if (!block || typeof block !== "object")
|
|
32
|
+
for (const id of new Set(toolCallBlocks(message).map((block) => block.id))) {
|
|
33
|
+
const previous = announcers.get(id);
|
|
34
|
+
if (!previous) {
|
|
35
|
+
announcers.set(id, [message]);
|
|
28
36
|
continue;
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
duplicates.add(candidate.id);
|
|
34
|
-
else
|
|
35
|
-
seen.add(candidate.id);
|
|
37
|
+
}
|
|
38
|
+
if (previous.some((earlier) => isSameAssistantTurn(earlier, message)))
|
|
39
|
+
duplicates.add(id);
|
|
40
|
+
previous.push(message);
|
|
36
41
|
}
|
|
37
42
|
}
|
|
38
43
|
return [...duplicates];
|
|
39
44
|
}
|
|
40
|
-
/** Throw a descriptive error when context carries
|
|
45
|
+
/** Throw a descriptive error when context carries the same assistant turn more than once. */
|
|
41
46
|
export function assertToolPairingInvariant(messages) {
|
|
42
47
|
const duplicates = findDuplicateToolCallIds(messages);
|
|
43
48
|
if (duplicates.length === 0)
|
|
@@ -47,4 +52,70 @@ export function assertToolPairingInvariant(messages) {
|
|
|
47
52
|
`${duplicates.join(", ")} ${plural ? "appear" : "appears"} in more than one assistant message. ` +
|
|
48
53
|
"The request was not sent.");
|
|
49
54
|
}
|
|
55
|
+
const EMPTY_TOOL_CALL_ID_BASE = "call";
|
|
56
|
+
function uniqueToolCallId(original, turn, used) {
|
|
57
|
+
const base = `${original || EMPTY_TOOL_CALL_ID_BASE}_${turn}`;
|
|
58
|
+
let candidate = base;
|
|
59
|
+
for (let attempt = 1; used.has(candidate); attempt++)
|
|
60
|
+
candidate = `${base}_${attempt}`;
|
|
61
|
+
return candidate;
|
|
62
|
+
}
|
|
63
|
+
function needsToolCallRename(blocks, used) {
|
|
64
|
+
const seen = new Set();
|
|
65
|
+
for (const { id } of blocks) {
|
|
66
|
+
if (id === "" || used.has(id) || seen.has(id))
|
|
67
|
+
return true;
|
|
68
|
+
seen.add(id);
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Give every tool call a non-empty id that no earlier call in the context uses.
|
|
74
|
+
*
|
|
75
|
+
* A reused or empty id is renamed after its assistant turn, and the tool results
|
|
76
|
+
* following that turn (up to the next assistant message) are renamed with it in
|
|
77
|
+
* call order. Renaming depends only on earlier messages, so the derived ids stay
|
|
78
|
+
* stable as the conversation grows and do not invalidate provider prompt caches.
|
|
79
|
+
* Messages that need no change are returned as the same objects.
|
|
80
|
+
*/
|
|
81
|
+
export function uniquifyToolCallIds(messages) {
|
|
82
|
+
const used = new Set();
|
|
83
|
+
let renamedResultIds;
|
|
84
|
+
let changed = false;
|
|
85
|
+
let turn = 0;
|
|
86
|
+
const uniquified = messages.map((message) => {
|
|
87
|
+
if (message.role === "assistant") {
|
|
88
|
+
turn++;
|
|
89
|
+
renamedResultIds = undefined;
|
|
90
|
+
const blocks = toolCallBlocks(message);
|
|
91
|
+
if (!needsToolCallRename(blocks, used)) {
|
|
92
|
+
for (const block of blocks)
|
|
93
|
+
used.add(block.id);
|
|
94
|
+
return message;
|
|
95
|
+
}
|
|
96
|
+
const pairing = new Map();
|
|
97
|
+
const content = message.content.map((block) => {
|
|
98
|
+
if (!isToolCallBlock(block))
|
|
99
|
+
return block;
|
|
100
|
+
const id = block.id !== "" && !used.has(block.id) ? block.id : uniqueToolCallId(block.id, turn, used);
|
|
101
|
+
used.add(id);
|
|
102
|
+
pairing.set(block.id, [...(pairing.get(block.id) ?? []), id]);
|
|
103
|
+
return id === block.id ? block : { ...block, id };
|
|
104
|
+
});
|
|
105
|
+
renamedResultIds = pairing;
|
|
106
|
+
changed = true;
|
|
107
|
+
return { ...message, content };
|
|
108
|
+
}
|
|
109
|
+
if (message.role !== "toolResult" || !renamedResultIds)
|
|
110
|
+
return message;
|
|
111
|
+
const toolCallId = message.toolCallId;
|
|
112
|
+
if (typeof toolCallId !== "string")
|
|
113
|
+
return message;
|
|
114
|
+
const id = renamedResultIds.get(toolCallId)?.shift();
|
|
115
|
+
if (id === undefined || id === toolCallId)
|
|
116
|
+
return message;
|
|
117
|
+
return { ...message, toolCallId: id };
|
|
118
|
+
});
|
|
119
|
+
return changed ? uniquified : messages;
|
|
120
|
+
}
|
|
50
121
|
//# sourceMappingURL=context-tool-pairing.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-tool-pairing.js","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,wBAAwB,CAAC,QAAiC;IACzE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;YAAE,SAAS;QAC3C,IAAK,OAA4C,CAAC,kBAAkB,KAAK,IAAI;YAAE,SAAS;QACxF,MAAM,OAAO,GAAI,OAAiC,CAAC,OAAO,CAAC;QAC3D,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;YAAE,SAAS;QACtC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;gBAAE,SAAS;YAClD,MAAM,SAAS,GAAG,KAAyC,CAAC;YAC5D,IAAI,SAAS,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,SAAS,CAAC,EAAE,KAAK,QAAQ;gBAAE,SAAS;YAChF,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;gBAAE,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;;gBACpD,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAC7B,CAAC;IACF,CAAC;IACD,OAAO,CAAC,GAAG,UAAU,CAAC,CAAC;AACxB,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,0BAA0B,CAAC,QAAiC;IAC3E,MAAM,UAAU,GAAG,wBAAwB,CAAC,QAAQ,CAAC,CAAC;IACtD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IACpC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;IACrC,MAAM,IAAI,KAAK,CACd,+DAA+D,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG;QACtF,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,uCAAuC;QAChG,2BAA2B,CAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\n/**\n * Structural tool-pairing guard for provider-bound context.\n *\n * `repairOrphanToolResults` already collapses the recoverable forms of this\n * invariant at conversion time: orphaned or duplicate `tool_result` blocks and\n * tool calls interrupted before their result was persisted. None need to reach\n * the provider.\n *\n * A `tool_use` id announced by more than one assistant message is a different\n * problem. It means the transcript itself carries the same assistant turn twice,\n * so there is no safe repair — dropping either copy guesses at which tool results\n * belong to it. The provider answers that with an opaque 400 that kills the turn,\n * so fail here instead, naming the ids.\n */\nexport function findDuplicateToolCallIds(messages: readonly AgentMessage[]): string[] {\n\tconst seen = new Set<string>();\n\tconst duplicates = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\") continue;\n\t\tif ((message as { excludeFromContext?: boolean }).excludeFromContext === true) continue;\n\t\tconst content = (message as { content?: unknown }).content;\n\t\tif (!Array.isArray(content)) continue;\n\t\tfor (const block of content) {\n\t\t\tif (!block || typeof block !== \"object\") continue;\n\t\t\tconst candidate = block as { type?: unknown; id?: unknown };\n\t\t\tif (candidate.type !== \"toolCall\" || typeof candidate.id !== \"string\") continue;\n\t\t\tif (seen.has(candidate.id)) duplicates.add(candidate.id);\n\t\t\telse seen.add(candidate.id);\n\t\t}\n\t}\n\treturn [...duplicates];\n}\n\n/** Throw a descriptive error when context carries a tool call id more than once. */\nexport function assertToolPairingInvariant(messages: readonly AgentMessage[]): void {\n\tconst duplicates = findDuplicateToolCallIds(messages);\n\tif (duplicates.length === 0) return;\n\tconst plural = duplicates.length > 1;\n\tthrow new Error(\n\t\t`Context is structurally invalid for the provider: tool call ${plural ? \"ids\" : \"id\"} ` +\n\t\t\t`${duplicates.join(\", \")} ${plural ? \"appear\" : \"appears\"} in more than one assistant message. ` +\n\t\t\t\"The request was not sent.\",\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-tool-pairing.js","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AA6BA,SAAS,eAAe,CAAC,KAAc;IACtC,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,SAAS,GAAG,KAAyC,CAAC;IAC5D,OAAO,SAAS,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,SAAS,CAAC,EAAE,KAAK,QAAQ,CAAC;AAC1E,CAAC;AAED,SAAS,cAAc,CAAC,OAAqB;IAC5C,MAAM,OAAO,GAAI,OAAiC,CAAC,OAAO,CAAC;IAC3D,OAAO,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACtE,CAAC;AAED,SAAS,UAAU,CAAC,OAAqB;IACxC,MAAM,EAAE,GAAI,OAAoC,CAAC,UAAU,CAAC;IAC5D,OAAO,OAAO,EAAE,KAAK,QAAQ,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC7D,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAmB,EAAE,MAAoB;IACrE,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,IAAI,CAAC;IAClC,MAAM,aAAa,GAAG,UAAU,CAAC,KAAK,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,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;gBAC9D,OAAO,EAAE,KAAK,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,EAAE,EAAE,CAAC;YACnD,CAAC,CAAC,CAAC;YACH,gBAAgB,GAAG,OAAO,CAAC;YAC3B,OAAO,GAAG,IAAI,CAAC;YACf,OAAO,EAAE,GAAG,OAAO,EAAE,OAAO,EAAc,CAAC;QAC5C,CAAC;QACD,IAAI,OAAO,CAAC,IAAI,KAAK,YAAY,IAAI,CAAC,gBAAgB;YAAE,OAAO,OAAO,CAAC;QACvE,MAAM,UAAU,GAAI,OAAoC,CAAC,UAAU,CAAC;QACpE,IAAI,OAAO,UAAU,KAAK,QAAQ;YAAE,OAAO,OAAO,CAAC;QACnD,MAAM,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,CAAC;QACrD,IAAI,EAAE,KAAK,SAAS,IAAI,EAAE,KAAK,UAAU;YAAE,OAAO,OAAO,CAAC;QAC1D,OAAO,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,EAAE,EAAc,CAAC;IACnD,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\n/**\n * Structural tool-pairing guard and repair for provider-bound context.\n *\n * `repairOrphanToolResults` already collapses the recoverable forms of this\n * invariant at conversion time: orphaned or duplicate `tool_result` blocks and\n * tool calls interrupted before their result was persisted. None need to reach\n * the provider.\n *\n * Some models (Kimi numbers calls `bash:0`, `bash:1`, … from zero in every\n * response) or providers (no id at all) reuse a tool call id across separate\n * assistant turns. Each turn's results follow it directly, so pairing by\n * position is unambiguous: `uniquifyToolCallIds` renames the reused ids in\n * derived context and leaves the transcript untouched.\n *\n * The same assistant turn appearing twice is a different problem. The transcript\n * itself is corrupt (#2051), so there is no safe repair — dropping either copy\n * guesses at which tool results belong to it. The provider answers that with an\n * opaque 400 that kills the turn, so fail here instead, naming the ids.\n */\n\ninterface ToolCallBlock {\n\ttype: \"toolCall\";\n\tid: string;\n\tname?: unknown;\n\targuments?: unknown;\n}\n\nfunction isToolCallBlock(block: unknown): block is ToolCallBlock {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; id?: unknown };\n\treturn candidate.type === \"toolCall\" && typeof candidate.id === \"string\";\n}\n\nfunction toolCallBlocks(message: AgentMessage): ToolCallBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\treturn Array.isArray(content) ? content.filter(isToolCallBlock) : [];\n}\n\nfunction responseId(message: AgentMessage): string | undefined {\n\tconst id = (message as { responseId?: unknown }).responseId;\n\treturn typeof id === \"string\" && id !== \"\" ? id : undefined;\n}\n\nfunction isSameAssistantTurn(first: AgentMessage, second: AgentMessage): boolean {\n\tif (first === second) return true;\n\tconst firstResponse = responseId(first);\n\tconst secondResponse = responseId(second);\n\tif (firstResponse !== undefined && secondResponse !== undefined) return firstResponse === secondResponse;\n\treturn first.timestamp === second.timestamp && JSON.stringify(first) === JSON.stringify(second);\n}\n\nexport function findDuplicateToolCallIds(messages: readonly AgentMessage[]): string[] {\n\tconst announcers = new Map<string, AgentMessage[]>();\n\tconst duplicates = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\") continue;\n\t\tif ((message as { excludeFromContext?: boolean }).excludeFromContext === true) continue;\n\t\tfor (const id of new Set(toolCallBlocks(message).map((block) => block.id))) {\n\t\t\tconst previous = announcers.get(id);\n\t\t\tif (!previous) {\n\t\t\t\tannouncers.set(id, [message]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (previous.some((earlier) => isSameAssistantTurn(earlier, message))) duplicates.add(id);\n\t\t\tprevious.push(message);\n\t\t}\n\t}\n\treturn [...duplicates];\n}\n\n/** Throw a descriptive error when context carries the same assistant turn more than once. */\nexport function assertToolPairingInvariant(messages: readonly AgentMessage[]): void {\n\tconst duplicates = findDuplicateToolCallIds(messages);\n\tif (duplicates.length === 0) return;\n\tconst plural = duplicates.length > 1;\n\tthrow new Error(\n\t\t`Context is structurally invalid for the provider: tool call ${plural ? \"ids\" : \"id\"} ` +\n\t\t\t`${duplicates.join(\", \")} ${plural ? \"appear\" : \"appears\"} in more than one assistant message. ` +\n\t\t\t\"The request was not sent.\",\n\t);\n}\n\nconst EMPTY_TOOL_CALL_ID_BASE = \"call\";\n\nfunction uniqueToolCallId(original: string, turn: number, used: ReadonlySet<string>): string {\n\tconst base = `${original || EMPTY_TOOL_CALL_ID_BASE}_${turn}`;\n\tlet candidate = base;\n\tfor (let attempt = 1; used.has(candidate); attempt++) candidate = `${base}_${attempt}`;\n\treturn candidate;\n}\n\nfunction needsToolCallRename(blocks: readonly ToolCallBlock[], used: ReadonlySet<string>): boolean {\n\tconst seen = new Set<string>();\n\tfor (const { id } of blocks) {\n\t\tif (id === \"\" || used.has(id) || seen.has(id)) return true;\n\t\tseen.add(id);\n\t}\n\treturn false;\n}\n\n/**\n * Give every tool call a non-empty id that no earlier call in the context uses.\n *\n * A reused or empty id is renamed after its assistant turn, and the tool results\n * following that turn (up to the next assistant message) are renamed with it in\n * call order. Renaming depends only on earlier messages, so the derived ids stay\n * stable as the conversation grows and do not invalidate provider prompt caches.\n * Messages that need no change are returned as the same objects.\n */\nexport function uniquifyToolCallIds<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tconst used = new Set<string>();\n\tlet renamedResultIds: Map<string, string[]> | undefined;\n\tlet changed = false;\n\tlet turn = 0;\n\tconst uniquified = messages.map((message): TMessage => {\n\t\tif (message.role === \"assistant\") {\n\t\t\tturn++;\n\t\t\trenamedResultIds = undefined;\n\t\t\tconst blocks = toolCallBlocks(message);\n\t\t\tif (!needsToolCallRename(blocks, used)) {\n\t\t\t\tfor (const block of blocks) used.add(block.id);\n\t\t\t\treturn message;\n\t\t\t}\n\t\t\tconst pairing = new Map<string, string[]>();\n\t\t\tconst content = (message as { content: unknown[] }).content.map((block) => {\n\t\t\t\tif (!isToolCallBlock(block)) return block;\n\t\t\t\tconst id = block.id !== \"\" && !used.has(block.id) ? block.id : uniqueToolCallId(block.id, turn, used);\n\t\t\t\tused.add(id);\n\t\t\t\tpairing.set(block.id, [...(pairing.get(block.id) ?? []), id]);\n\t\t\t\treturn id === block.id ? block : { ...block, id };\n\t\t\t});\n\t\t\trenamedResultIds = pairing;\n\t\t\tchanged = true;\n\t\t\treturn { ...message, content } as TMessage;\n\t\t}\n\t\tif (message.role !== \"toolResult\" || !renamedResultIds) return message;\n\t\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\t\tif (typeof toolCallId !== \"string\") return message;\n\t\tconst id = renamedResultIds.get(toolCallId)?.shift();\n\t\tif (id === undefined || id === toolCallId) return message;\n\t\treturn { ...message, toolCallId: id } as TMessage;\n\t});\n\treturn changed ? uniquified : messages;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution-model-router.d.ts","sourceRoot":"","sources":["../../src/core/execution-model-router.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,KAAK,GAAG,EAIR,KAAK,KAAK,EACV,MAAM,gBAAgB,CAAC;AAGxB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAEN,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EAEtB,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"execution-model-router.d.ts","sourceRoot":"","sources":["../../src/core/execution-model-router.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,KAAK,GAAG,EAIR,KAAK,KAAK,EACV,MAAM,gBAAgB,CAAC;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,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7C,WAAW,CAAC,EAAE,SAAS,gBAAgB,EAAE,CAAC;IAC1C,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,kEAAkE;IAClE,SAAS,CAAC,EAAE,iBAAiB,CAAC;CAC9B,GAAG,OAAO,CAAC,UAAU,CAAC,CA2LtB"}
|
|
@@ -4,7 +4,7 @@ import { containsKnownEnvCredential, getSupportedThinkingLevels, isModelType, }
|
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
import { getDocsPath } from "../config.js";
|
|
6
6
|
import { eligiblePair, parseModelConstraints, } from "./model-routing-constraints.js";
|
|
7
|
-
import { modelRoutingTask } from "./model-routing-task.js";
|
|
7
|
+
import { jsonBytes, MODEL_ROUTING_TASK_BYTES, modelRoutingTask, ROUTING_REQUEST_BYTES, TRUNCATED_MARKER, truncateToBytes, } from "./model-routing-task.js";
|
|
8
8
|
import { resolveRouterModel, routeModel } from "./structured-output/index.js";
|
|
9
9
|
/**
|
|
10
10
|
* Total auto-routing inference failure: Jev and the chat structured-output
|
|
@@ -56,14 +56,25 @@ Price is per task. Candidate cost is USD per million tokens, and roles differ in
|
|
|
56
56
|
|
|
57
57
|
An explicit user request wins over these defaults, but the requested level must exist for the selected catalog entry. Do not invent unsupported suffixes. If \`xhigh\` is unavailable, use \`high\` rather than automatically promoting to \`max\`; choose another catalog model or leave the stage unpinned if neither fits.
|
|
58
58
|
`;
|
|
59
|
-
//
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
// nine-candidate question.
|
|
59
|
+
// Keeps the shipped evals snapshot small enough to reach Jev intact alongside the
|
|
60
|
+
// guide, a full task excerpt, and a small candidate question. Larger candidate
|
|
61
|
+
// questions truncate the routing copy instead; see fitRoutingState.
|
|
63
62
|
export const MODEL_SELECTION_EVALS_JSON_BYTES = 14_200;
|
|
64
63
|
const EVALS_BUDGET_ERROR = `Auto routing requires a nonempty evals.md document within ${MODEL_SELECTION_EVALS_JSON_BYTES.toLocaleString("en-US")} JSON-encoded bytes. Repair the Atomic installation or select a concrete execution model.`;
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
// Decision policy, key names and JSON framing the classifier transport adds.
|
|
65
|
+
const ROUTING_WIRE_OVERHEAD_BYTES = 1_000;
|
|
66
|
+
const PAIR_QUESTION = "Which eligible model and reasoning effort best suit this task and agent role, considering the model_selection_guide role tiers, evals, and candidate capabilities and prices? Prefer cheaper candidates for exploration and routine implementation and stronger ones for review and verification. Candidate cost is USD per million tokens, not benchmark task cost.";
|
|
67
|
+
/**
|
|
68
|
+
* Truncate the routing copy of the task, then evals, so state plus the candidate
|
|
69
|
+
* question fits ROUTING_REQUEST_BYTES. Candidates, agent and guide stay intact.
|
|
70
|
+
*/
|
|
71
|
+
function fitRoutingState(state, criteria) {
|
|
72
|
+
const fixed = Buffer.byteLength(JSON.stringify({ ...state, task: "", evals: "", instructions, question: PAIR_QUESTION, criteria }), "utf8") + ROUTING_WIRE_OVERHEAD_BYTES;
|
|
73
|
+
const room = Math.max(0, ROUTING_REQUEST_BYTES - fixed);
|
|
74
|
+
const evalsMarkerBytes = jsonBytes(TRUNCATED_MARKER);
|
|
75
|
+
const task = modelRoutingTask(state.task, Math.max(0, Math.min(MODEL_ROUTING_TASK_BYTES, room - evalsMarkerBytes)));
|
|
76
|
+
const evals = truncateToBytes(state.evals, Math.max(evalsMarkerBytes, room - jsonBytes(task)));
|
|
77
|
+
return { ...state, task, evals };
|
|
67
78
|
}
|
|
68
79
|
async function readModelSelectionEvals(signal) {
|
|
69
80
|
try {
|
|
@@ -129,9 +140,8 @@ export async function routeExecutionModel(input) {
|
|
|
129
140
|
/\bBearer\s+[A-Za-z0-9._~+/-]{8,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:sk|ghp|github_pat)[-_][A-Za-z0-9_-]{16,}/i.test(serialized))
|
|
130
141
|
throw new Error("Auto routing context contains credential material. Remove secrets before retrying.");
|
|
131
142
|
// Screen the full task first, even credentials in text the router will omit.
|
|
132
|
-
//
|
|
143
|
+
// Truncation only affects the routing request, never the execution prompt,
|
|
133
144
|
// so it is not surfaced to the user.
|
|
134
|
-
state.task = modelRoutingTask(state.task);
|
|
135
145
|
const ranked = [];
|
|
136
146
|
// Degrade only to a current chat model that is available and eligible under
|
|
137
147
|
// the same constraints, restored through the normal selection path (#3206).
|
|
@@ -182,13 +192,13 @@ export async function routeExecutionModel(input) {
|
|
|
182
192
|
settings,
|
|
183
193
|
modelRegistry: ctx.modelRegistry,
|
|
184
194
|
currentModel: ctx.model,
|
|
185
|
-
state,
|
|
195
|
+
state: fitRoutingState(state, criteria),
|
|
186
196
|
instructions,
|
|
187
197
|
schema,
|
|
188
198
|
classifier: {
|
|
189
199
|
questions: {
|
|
190
200
|
pair: {
|
|
191
|
-
instructions:
|
|
201
|
+
instructions: PAIR_QUESTION,
|
|
192
202
|
criteria,
|
|
193
203
|
},
|
|
194
204
|
},
|