@kingsoftcloud/agentkit-harness-node 0.0.13 → 0.0.15
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/dist/index.mjs +225 -102
- package/dist/rpc-entry.mjs +231 -108
- package/package.json +5 -2
- package/src/native/activity-status.mjs +32 -1
- package/src/native/approval-preflight.mjs +35 -0
- package/src/native/child-history.mjs +5 -2
- package/src/native/child-owner.mjs +46 -11
- package/src/native/children.mjs +30 -8
- package/src/native/conversation-presentation.mjs +31 -0
- package/src/native/dsh-turn-runtime.mjs +28 -3
- package/src/native/local-command-policy-worker.mjs +2 -1
- package/src/native/local-command-tools.mjs +6 -1
- package/src/native/model-anthropic.mjs +6 -1
- package/src/native/model-openai-chat.mjs +17 -2
- package/src/native/model-port.mjs +13 -6
- package/src/native/model-provider-compat.mjs +16 -7
- package/src/native/model-provider-error.mjs +62 -0
- package/src/native/model-responses.mjs +15 -37
- package/src/native/python-grammar.mjs +14 -0
- package/src/native/python-syntax-worker.mjs +4 -3
- package/src/native/run-observation.mjs +2 -2
- package/src/native/session-tool-approval.mjs +91 -0
- package/src/native/sqlite-store.mjs +24 -0
- package/src/native/workspace-checkpoints.mjs +20 -5
- package/src/native/workspace-instructions.mjs +18 -3
- package/src/native/workspace-tools.mjs +2 -1
package/dist/rpc-entry.mjs
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
// packages/agentkit-harness-node/src/rpc-entry.mjs
|
|
4
4
|
import { parseArgs } from "node:util";
|
|
5
|
-
import { createHash as
|
|
5
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
6
6
|
import { realpathSync as realpathSync2 } from "node:fs";
|
|
7
7
|
import { resolve as resolvePath } from "node:path";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
9
|
import * as readline from "node:readline";
|
|
10
|
-
import { NativeKernel, configure, initialSnapshot, canonical as
|
|
10
|
+
import { NativeKernel, configure, initialSnapshot, canonical as canonical9, terminal as terminal3, runKey as runKey2, NativeError, isNativeError } from "@kingsoftcloud/agentkit-harness-core";
|
|
11
11
|
|
|
12
12
|
// packages/agentkit-harness-node/src/native/sqlite-session-inbox.mjs
|
|
13
13
|
import { appendSessionInjection, canonical, invariant, parseNativeJson } from "@kingsoftcloud/agentkit-harness-core";
|
|
@@ -384,6 +384,18 @@ function nativeContextStatus(record, { driving = false } = {}) {
|
|
|
384
384
|
|
|
385
385
|
// packages/agentkit-harness-node/src/native/activity-status.mjs
|
|
386
386
|
import { createHash as createHash2 } from "node:crypto";
|
|
387
|
+
import { canonical as canonical4 } from "@kingsoftcloud/agentkit-harness-core";
|
|
388
|
+
var settledCommandStates = /* @__PURE__ */ new Set(["completed", "failed", "canceled", "timed_out", "output_limit"]);
|
|
389
|
+
function foregroundReceiptState(record, ref, intent) {
|
|
390
|
+
if (ref.sourceRunId !== record.snapshot.runId || intent?.kind !== "tool" || intent.payload.calls?.length !== 1) return null;
|
|
391
|
+
const definition = record.configuration?.tools.find((tool) => tool.name === intent.payload.calls[0].name);
|
|
392
|
+
if (definition?.backgroundCommandPolicy !== "owned-command-launch/v1") return null;
|
|
393
|
+
const receipt = record.receipts?.find((row) => row.operationKey === ref.operationKey);
|
|
394
|
+
const results = receipt?.result?.results;
|
|
395
|
+
const result = results?.length === 1 ? results[0] : null;
|
|
396
|
+
if (receipt?.status !== "committed" || result?.status !== "ok" || result.backgroundCommandFinished !== true || !result.backgroundCommandRef || canonical4(result.backgroundCommandRef) !== canonical4(ref) || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true || !settledCommandStates.has(result.content.status)) return null;
|
|
397
|
+
return result.content.status;
|
|
398
|
+
}
|
|
387
399
|
function nativeActivityStatus(record, { driving = false } = {}) {
|
|
388
400
|
if (!record) return null;
|
|
389
401
|
const { snapshot } = record;
|
|
@@ -406,7 +418,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
|
|
|
406
418
|
id: ref.taskId,
|
|
407
419
|
runId: snapshot.runId,
|
|
408
420
|
title: call?.arguments.command?.slice(0, 512) || ref.taskId,
|
|
409
|
-
state: observed?.status ?? "unknown",
|
|
421
|
+
state: observed?.status ?? foregroundReceiptState(record, ref, intent) ?? "unknown",
|
|
410
422
|
canCancel: false
|
|
411
423
|
};
|
|
412
424
|
});
|
|
@@ -427,14 +439,14 @@ function nativeActivityStatus(record, { driving = false } = {}) {
|
|
|
427
439
|
}
|
|
428
440
|
|
|
429
441
|
// packages/agentkit-harness-node/src/native/a2a-receipt-source.mjs
|
|
430
|
-
import { canonical as
|
|
442
|
+
import { canonical as canonical5 } from "@kingsoftcloud/agentkit-harness-core";
|
|
431
443
|
function nativeA2aReceiptWaitSource(record) {
|
|
432
444
|
const snapshot = record?.snapshot, marker = snapshot?.toolReconciliation;
|
|
433
445
|
if (snapshot?.phase !== "awaiting_reconciliation" || snapshot.pendingIntent !== null || marker?.contract !== "agentkit.tool-receipt-observation/v1") return null;
|
|
434
446
|
const intent = record.intents.find((item) => item.operationKey === marker.operationKey);
|
|
435
447
|
const call = intent?.payload.calls?.[0], definition = record.configuration.tools.find((item) => item.name === call?.name);
|
|
436
448
|
const receipt = record.receipts.find((item) => item.operationKey === marker.operationKey);
|
|
437
|
-
if (call?.name !== "call_a2a_agent" || definition?.recoveryPolicy !== "receipt-observation/v1" || intent.kind !== "tool" || intent.status !== "running" || intent.payload.calls.length !== 1 || !Number.isSafeInteger(intent.claimedFence) || intent.claimedFence <= 0 || call.callId !== marker.callId ||
|
|
449
|
+
if (call?.name !== "call_a2a_agent" || definition?.recoveryPolicy !== "receipt-observation/v1" || intent.kind !== "tool" || intent.status !== "running" || intent.payload.calls.length !== 1 || !Number.isSafeInteger(intent.claimedFence) || intent.claimedFence <= 0 || call.callId !== marker.callId || canonical5(snapshot.pendingTools.slice(0, 1)) !== canonical5([call]) || !receipt || !(receipt.status === "uncertain" || receipt.result.results?.[0]?.status === "uncertain")) return null;
|
|
438
450
|
return { intent, call, definition };
|
|
439
451
|
}
|
|
440
452
|
|
|
@@ -451,7 +463,7 @@ function canCloseNativeReadInterruption(record) {
|
|
|
451
463
|
|
|
452
464
|
// packages/agentkit-harness-node/src/native/run-observation.mjs
|
|
453
465
|
var NATIVE_RUN_OBSERVATION = "agentkit.native-run-observation/v1";
|
|
454
|
-
var NATIVE_COMMIT_PROJECTION = "agentkit.native-commit-projection/
|
|
466
|
+
var NATIVE_COMMIT_PROJECTION = "agentkit.native-commit-projection/v3";
|
|
455
467
|
function contextProjection(previous, record) {
|
|
456
468
|
let lastPlan = previous?.lastPlan ?? null, lastAdmission = previous?.lastAdmission ?? null;
|
|
457
469
|
for (const event of record.events ?? []) if (event.kind === "context.planned") {
|
|
@@ -482,7 +494,8 @@ function observationHeader(s) {
|
|
|
482
494
|
"outcome",
|
|
483
495
|
"reason",
|
|
484
496
|
"pendingIntent",
|
|
485
|
-
"toolReconciliation"
|
|
497
|
+
"toolReconciliation",
|
|
498
|
+
"retryNotBefore"
|
|
486
499
|
].filter((key) => s[key] !== void 0).map((key) => [key, s[key]]));
|
|
487
500
|
header.diagnostics = Object.fromEntries(["providerUsageIncomplete", "descendantUsageIncomplete", "lastModelFailure"].filter((key) => s.diagnostics[key] !== void 0).map((key) => [key, s.diagnostics[key]]));
|
|
488
501
|
return header;
|
|
@@ -606,7 +619,7 @@ function advanceNativeRunCommitObservation(previous, state, changes) {
|
|
|
606
619
|
// packages/agentkit-harness-node/src/native/sqlite-store.mjs
|
|
607
620
|
import {
|
|
608
621
|
TransactionalRunStore,
|
|
609
|
-
canonical as
|
|
622
|
+
canonical as canonical6,
|
|
610
623
|
invariant as invariant3,
|
|
611
624
|
scopeKey,
|
|
612
625
|
runKey,
|
|
@@ -679,7 +692,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
679
692
|
for (const row of legacy) {
|
|
680
693
|
const item = parseNativeJson2(row.data);
|
|
681
694
|
invariant3(typeof item.fingerprint === "string", "invalid_commit_fingerprint");
|
|
682
|
-
compact.run(
|
|
695
|
+
compact.run(canonical6({ ...item, fingerprint: commitFingerprint(item.fingerprint) }), row.rowid);
|
|
683
696
|
}
|
|
684
697
|
if (versions.length && versions[0].version === 1) db.prepare("UPDATE native_schema SET version=2").run();
|
|
685
698
|
db.exec("COMMIT");
|
|
@@ -705,7 +718,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
705
718
|
scopeKey(scope);
|
|
706
719
|
const row = db.prepare(`SELECT data FROM native_runs
|
|
707
720
|
WHERE json_extract(data,'$.snapshot.scope')=? AND json_extract(data,'$.snapshot.sessionId')=?
|
|
708
|
-
ORDER BY rowid DESC LIMIT 1`).get(
|
|
721
|
+
ORDER BY rowid DESC LIMIT 1`).get(canonical6(scope), sessionId);
|
|
709
722
|
return row ? parseNativeJson2(row.data).snapshot : null;
|
|
710
723
|
};
|
|
711
724
|
const read = (key) => {
|
|
@@ -774,14 +787,14 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
774
787
|
return row ? parseNativeJson2(row.data) : null;
|
|
775
788
|
};
|
|
776
789
|
const writeDeliveryHead = (key, snapshot) => db.prepare(`INSERT INTO native_delivery_heads VALUES (?,?)
|
|
777
|
-
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key,
|
|
790
|
+
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(deliveryJournalHead(snapshot)));
|
|
778
791
|
const appendDelivery = (key, evidence, snapshot) => {
|
|
779
792
|
const insert = db.prepare(`INSERT INTO native_delivery_items VALUES (?,?,?,?)
|
|
780
793
|
ON CONFLICT(run_key,collection,item_key) DO UPDATE SET data=CASE
|
|
781
794
|
WHEN native_delivery_items.collection='tools'
|
|
782
795
|
OR native_delivery_items.collection='outcomes' AND native_delivery_items.data='"not_dispatched"'
|
|
783
796
|
THEN native_delivery_items.data ELSE excluded.data END`);
|
|
784
|
-
for (const row of sessionDeliveryEntries(evidence)) insert.run(key, row.collection, row.key,
|
|
797
|
+
for (const row of sessionDeliveryEntries(evidence)) insert.run(key, row.collection, row.key, canonical6(row.data));
|
|
785
798
|
writeDeliveryHead(key, snapshot);
|
|
786
799
|
};
|
|
787
800
|
const rebuildDelivery = (key, record) => {
|
|
@@ -790,21 +803,21 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
790
803
|
};
|
|
791
804
|
const persist = (key, previous, record) => {
|
|
792
805
|
const { events, intents, receipts, commands, commits, ...metadata } = record;
|
|
793
|
-
db.prepare("INSERT INTO native_runs(key,data) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET data=excluded.data").run(key,
|
|
806
|
+
db.prepare("INSERT INTO native_runs(key,data) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET data=excluded.data").run(key, canonical6(metadata));
|
|
794
807
|
invariant3(events.length >= (previous?.events.length ?? 0), "events_immutable");
|
|
795
808
|
for (const event of events.slice(previous?.events.length ?? 0))
|
|
796
|
-
db.prepare("INSERT INTO native_events VALUES (?,?,?,?)").run(key, event.seq, event.eventId,
|
|
809
|
+
db.prepare("INSERT INTO native_events VALUES (?,?,?,?)").run(key, event.seq, event.eventId, canonical6(event));
|
|
797
810
|
for (const [collection, identify] of Object.entries(collections)) {
|
|
798
|
-
const old = new Map((previous?.[collection] ?? []).map((item) => [identify(item),
|
|
811
|
+
const old = new Map((previous?.[collection] ?? []).map((item) => [identify(item), canonical6(item)]));
|
|
799
812
|
invariant3(record[collection].length >= old.size, "ledger_items_immutable");
|
|
800
813
|
for (const item of record[collection]) {
|
|
801
|
-
const id = identify(item), data =
|
|
814
|
+
const id = identify(item), data = canonical6(item);
|
|
802
815
|
if (old.get(id) !== data) db.prepare("INSERT INTO native_items VALUES (?,?,?,?) ON CONFLICT(run_key,collection,item_key) DO UPDATE SET data=excluded.data").run(key, collection, id, data);
|
|
803
816
|
}
|
|
804
817
|
}
|
|
805
818
|
if (!previous) inbox.consume(record.snapshot);
|
|
806
819
|
db.prepare(`INSERT INTO native_run_observations VALUES (?,?)
|
|
807
|
-
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key,
|
|
820
|
+
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(projectNativeRunObservation(record)));
|
|
808
821
|
rebuildDelivery(key, record);
|
|
809
822
|
beforeCommit?.({ key, record });
|
|
810
823
|
};
|
|
@@ -861,7 +874,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
861
874
|
const row = db.prepare("SELECT data FROM native_run_observations WHERE run_key=?").get(key);
|
|
862
875
|
const observation = row ? parseNativeJson2(row.data) : null;
|
|
863
876
|
const exceptional = !current || ["interrupted", "awaiting_reconciliation", "reconciling_tool"].some((phase) => current.snapshot.phase === phase || batch.snapshot.phase === phase);
|
|
864
|
-
const compatible = observation?.contract === NATIVE_RUN_OBSERVATION && observation.commitProjection?.contract === NATIVE_COMMIT_PROJECTION && Array.isArray(observation.commitProjection?.tools?.calls) && Array.isArray(observation.facts?.toolOutcomes) && observation.snapshot.revision === current?.snapshot.revision && observation.snapshot.eventSeq === current?.snapshot.eventSeq && observation.snapshot.configDigest === current?.snapshot.configDigest && observation.snapshot.runId === current?.snapshot.runId && observation.snapshot.sessionId === current?.snapshot.sessionId &&
|
|
877
|
+
const compatible = observation?.contract === NATIVE_RUN_OBSERVATION && observation.commitProjection?.contract === NATIVE_COMMIT_PROJECTION && Array.isArray(observation.commitProjection?.tools?.calls) && Array.isArray(observation.facts?.toolOutcomes) && observation.snapshot.revision === current?.snapshot.revision && observation.snapshot.eventSeq === current?.snapshot.eventSeq && observation.snapshot.configDigest === current?.snapshot.configDigest && observation.snapshot.runId === current?.snapshot.runId && observation.snapshot.sessionId === current?.snapshot.sessionId && canonical6(observation.snapshot.scope) === canonical6(current?.snapshot.scope);
|
|
865
878
|
if (exceptional || !compatible || !matchesDeliveryJournal(deliveryHead(key), current.snapshot)) {
|
|
866
879
|
const previous = read(key), result = change(previous ? projectLedgerCommitState(previous, batch) : null);
|
|
867
880
|
if (result.changes) persist(key, previous, applyLedgerCommitChanges(previous, result.changes));
|
|
@@ -871,16 +884,16 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
871
884
|
const { changes, value } = change(current);
|
|
872
885
|
if (changes) {
|
|
873
886
|
const { commands, intents, existingReceiptKeys, existingEventIds, duplicateCommit, ...metadata } = current;
|
|
874
|
-
db.prepare("UPDATE native_runs SET data=? WHERE key=?").run(
|
|
887
|
+
db.prepare("UPDATE native_runs SET data=? WHERE key=?").run(canonical6({ ...metadata, snapshot: changes.snapshot }), key);
|
|
875
888
|
const eventInsert = db.prepare("INSERT INTO native_events VALUES (?,?,?,?)");
|
|
876
|
-
for (const event of changes.events) eventInsert.run(key, event.seq, event.eventId,
|
|
889
|
+
for (const event of changes.events) eventInsert.run(key, event.seq, event.eventId, canonical6(event));
|
|
877
890
|
const itemInsert = db.prepare("INSERT INTO native_items VALUES (?,?,?,?)");
|
|
878
891
|
for (const [collection, items] of [["intents", changes.intents], ["receipts", changes.receipts], ["commits", [changes.commit]]])
|
|
879
|
-
for (const item of items) itemInsert.run(key, collection, collections[collection](item),
|
|
892
|
+
for (const item of items) itemInsert.run(key, collection, collections[collection](item), canonical6(item));
|
|
880
893
|
const commandUpdate = db.prepare("UPDATE native_items SET data=? WHERE run_key=? AND collection='commands' AND item_key=?");
|
|
881
|
-
for (const row2 of changes.commands) commandUpdate.run(
|
|
894
|
+
for (const row2 of changes.commands) commandUpdate.run(canonical6(row2), key, row2.command.commandId);
|
|
882
895
|
const advanced = advanceNativeRunCommitObservation(observation, current, changes);
|
|
883
|
-
db.prepare("UPDATE native_run_observations SET data=? WHERE run_key=?").run(
|
|
896
|
+
db.prepare("UPDATE native_run_observations SET data=? WHERE run_key=?").run(canonical6(advanced), key);
|
|
884
897
|
appendDelivery(key, {
|
|
885
898
|
events: changes.events,
|
|
886
899
|
receipts: changes.receipts,
|
|
@@ -919,27 +932,27 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
919
932
|
const presentationCurrent = matchesDeliveryJournal(deliveryHead(key), current.snapshot);
|
|
920
933
|
const cached = db.prepare("SELECT data FROM native_run_observations WHERE run_key=?").get(key);
|
|
921
934
|
let observation = cached ? parseNativeJson2(cached.data) : null;
|
|
922
|
-
if (!observation || observation.contract !== NATIVE_RUN_OBSERVATION || observation.commitProjection?.contract !== NATIVE_COMMIT_PROJECTION || !Array.isArray(observation.commitProjection?.tools?.calls) || !Array.isArray(observation.facts?.toolOutcomes) || observation.snapshot.revision !== current.snapshot.revision || observation.snapshot.eventSeq !== current.snapshot.eventSeq || observation.snapshot.configDigest !== current.snapshot.configDigest || observation.snapshot.runId !== current.snapshot.runId || observation.snapshot.sessionId !== current.snapshot.sessionId ||
|
|
935
|
+
if (!observation || observation.contract !== NATIVE_RUN_OBSERVATION || observation.commitProjection?.contract !== NATIVE_COMMIT_PROJECTION || !Array.isArray(observation.commitProjection?.tools?.calls) || !Array.isArray(observation.facts?.toolOutcomes) || observation.snapshot.revision !== current.snapshot.revision || observation.snapshot.eventSeq !== current.snapshot.eventSeq || observation.snapshot.configDigest !== current.snapshot.configDigest || observation.snapshot.runId !== current.snapshot.runId || observation.snapshot.sessionId !== current.snapshot.sessionId || canonical6(observation.snapshot.scope) !== canonical6(current.snapshot.scope))
|
|
923
936
|
observation = projectNativeRunObservation(read(key));
|
|
924
937
|
if (changes.claim) {
|
|
925
938
|
const { snapshot, intent } = changes.claim;
|
|
926
|
-
db.prepare("UPDATE native_runs SET data=json_set(data,'$.snapshot',json(?)) WHERE key=?").run(
|
|
939
|
+
db.prepare("UPDATE native_runs SET data=json_set(data,'$.snapshot',json(?)) WHERE key=?").run(canonical6(snapshot), key);
|
|
927
940
|
const result = db.prepare(`UPDATE native_items SET data=?
|
|
928
|
-
WHERE run_key=? AND collection='intents' AND item_key=?`).run(
|
|
941
|
+
WHERE run_key=? AND collection='intents' AND item_key=?`).run(canonical6(intent), key, intent.operationKey);
|
|
929
942
|
invariant3(result.changes === 1, "pending_intent_missing");
|
|
930
943
|
}
|
|
931
944
|
if (changes.commands) {
|
|
932
|
-
const previous = new Map(current.commands.map((row) => [row.command.commandId,
|
|
945
|
+
const previous = new Map(current.commands.map((row) => [row.command.commandId, canonical6(row)]));
|
|
933
946
|
for (const row of changes.commands) {
|
|
934
|
-
const data =
|
|
947
|
+
const data = canonical6(row), id = row.command.commandId;
|
|
935
948
|
if (previous.get(id) !== data) db.prepare(`INSERT INTO native_items VALUES (?,?,?,?)
|
|
936
949
|
ON CONFLICT(run_key,collection,item_key) DO UPDATE SET data=excluded.data`).run(key, "commands", id, data);
|
|
937
950
|
}
|
|
938
951
|
}
|
|
939
|
-
if (changes.projections) db.prepare("UPDATE native_runs SET data=json_set(data,'$.projections',json(?)) WHERE key=?").run(
|
|
952
|
+
if (changes.projections) db.prepare("UPDATE native_runs SET data=json_set(data,'$.projections',json(?)) WHERE key=?").run(canonical6(changes.projections), key);
|
|
940
953
|
const updated = advanceNativeRunControlObservation(observation, current, changes);
|
|
941
954
|
db.prepare(`INSERT INTO native_run_observations VALUES (?,?)
|
|
942
|
-
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key,
|
|
955
|
+
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(updated));
|
|
943
956
|
if (presentationCurrent) writeDeliveryHead(key, changes.claim?.snapshot ?? current.snapshot);
|
|
944
957
|
}
|
|
945
958
|
db.exec("COMMIT");
|
|
@@ -957,7 +970,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
957
970
|
'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
|
|
958
971
|
'backgroundCommands',json_extract(data,'$.snapshot.backgroundCommands'), 'lease',json_extract(data,'$.lease')) AS head
|
|
959
972
|
FROM native_runs WHERE json_extract(data,'$.snapshot.scope')=? AND json_extract(data,'$.snapshot.sessionId')=?
|
|
960
|
-
ORDER BY rowid DESC LIMIT 1`).get(
|
|
973
|
+
ORDER BY rowid DESC LIMIT 1`).get(canonical6(scope), sessionId);
|
|
961
974
|
return row ? parseNativeJson2(row.head) : null;
|
|
962
975
|
},
|
|
963
976
|
projectionCursors: (key) => {
|
|
@@ -1033,7 +1046,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1033
1046
|
...row.retirement === null ? {} : { resourceRetirementReview: parseNativeJson2(row.retirement) }
|
|
1034
1047
|
} : null);
|
|
1035
1048
|
invariant3(row, "run_not_found");
|
|
1036
|
-
db.prepare(`UPDATE native_runs SET data=json_set(data,'$.lease',json(?),'$.fence',?) WHERE key=?`).run(
|
|
1049
|
+
db.prepare(`UPDATE native_runs SET data=json_set(data,'$.lease',json(?),'$.fence',?) WHERE key=?`).run(canonical6(record.lease), record.fence, key);
|
|
1037
1050
|
db.exec("COMMIT");
|
|
1038
1051
|
return value;
|
|
1039
1052
|
} catch (error) {
|
|
@@ -1084,7 +1097,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1084
1097
|
open2();
|
|
1085
1098
|
return db.prepare(`SELECT json_extract(data,'$.snapshot') AS snapshot FROM native_runs
|
|
1086
1099
|
WHERE json_extract(data,'$.snapshot.scope')=?
|
|
1087
|
-
${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(
|
|
1100
|
+
${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(canonical6(scope), ...sessionId === void 0 ? [] : [sessionId]).map((row) => parseNativeJson2(row.snapshot));
|
|
1088
1101
|
},
|
|
1089
1102
|
heads: (scope, sessionId) => {
|
|
1090
1103
|
open2();
|
|
@@ -1094,7 +1107,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1094
1107
|
'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
|
|
1095
1108
|
'backgroundCommands',json_extract(data,'$.snapshot.backgroundCommands'), 'lease',json_extract(data,'$.lease')) AS head
|
|
1096
1109
|
FROM native_runs WHERE json_extract(data,'$.snapshot.scope')=?
|
|
1097
|
-
${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(
|
|
1110
|
+
${sessionId === void 0 ? "" : "AND json_extract(data,'$.snapshot.sessionId')=?"} ORDER BY rowid`).all(canonical6(scope), ...sessionId === void 0 ? [] : [sessionId]).map((row) => parseNativeJson2(row.head));
|
|
1098
1111
|
},
|
|
1099
1112
|
values: () => {
|
|
1100
1113
|
open2();
|
|
@@ -1136,6 +1149,29 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1136
1149
|
}
|
|
1137
1150
|
}
|
|
1138
1151
|
});
|
|
1152
|
+
this.traceView = (scope, runId, after = 0) => {
|
|
1153
|
+
open2();
|
|
1154
|
+
invariant3(Number.isSafeInteger(after) && after >= 0, "invalid_trace_cursor");
|
|
1155
|
+
const key = runKey(scope, runId);
|
|
1156
|
+
db.exec("BEGIN");
|
|
1157
|
+
try {
|
|
1158
|
+
const row = db.prepare(`SELECT json_object(
|
|
1159
|
+
'scope',json_extract(data,'$.snapshot.scope'), 'runId',json_extract(data,'$.snapshot.runId'),
|
|
1160
|
+
'sessionId',json_extract(data,'$.snapshot.sessionId'), 'phase',json_extract(data,'$.snapshot.phase'),
|
|
1161
|
+
'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
|
|
1162
|
+
'usage',json_extract(data,'$.snapshot.usage'), 'outcome',json_extract(data,'$.snapshot.outcome')) AS snapshot
|
|
1163
|
+
FROM native_runs WHERE key=?`).get(key);
|
|
1164
|
+
invariant3(row, "run_not_found");
|
|
1165
|
+
const snapshot = parseNativeJson2(row.snapshot);
|
|
1166
|
+
invariant3(snapshot.runId === runId && canonical6(snapshot.scope) === canonical6(scope), "native_trace_identity_mismatch");
|
|
1167
|
+
const events = db.prepare("SELECT data FROM native_events WHERE run_key=? AND seq>? AND seq<=? ORDER BY seq").all(key, after, snapshot.eventSeq).map((row2) => parseNativeJson2(row2.data));
|
|
1168
|
+
db.exec("COMMIT");
|
|
1169
|
+
return { contract: "agentkit.native-trace-view/v1", snapshot, events };
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
db.exec("ROLLBACK");
|
|
1172
|
+
throw error;
|
|
1173
|
+
}
|
|
1174
|
+
};
|
|
1139
1175
|
this.sessionDeliveryState = (scope, runId) => {
|
|
1140
1176
|
open2();
|
|
1141
1177
|
const key = runKey(scope, runId);
|
|
@@ -1147,7 +1183,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1147
1183
|
invariant3(row, "run_not_found");
|
|
1148
1184
|
const snapshot = parseNativeJson2(row.snapshot), presence = parseNativeJson2(row.presence);
|
|
1149
1185
|
for (const [name, type] of Object.entries(presence)) if (type === null) delete snapshot[name];
|
|
1150
|
-
invariant3(snapshot.runId === runId &&
|
|
1186
|
+
invariant3(snapshot.runId === runId && canonical6(snapshot.scope) === canonical6(scope), "delivery_identity_mismatch");
|
|
1151
1187
|
return { snapshot, configuration: parseNativeJson2(row.configuration), projections: parseNativeJson2(row.projections) };
|
|
1152
1188
|
};
|
|
1153
1189
|
db.exec("BEGIN");
|
|
@@ -1171,11 +1207,11 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1171
1207
|
WHERE run_key=? AND collection='receipts' AND item_key=?`).get(path, path + ".status", path + ".context", path + ".content", key, reference.operationKey);
|
|
1172
1208
|
}
|
|
1173
1209
|
if (receipt?.status === "committed" && receipt.observed === "object") return {
|
|
1174
|
-
context: receipt.context === null ? { content:
|
|
1210
|
+
context: receipt.context === null ? { content: canonical6(parseNativeJson2(receipt.content)) } : toolContext2(parseNativeJson2(receipt.context)),
|
|
1175
1211
|
isError: receipt.resultStatus !== "ok"
|
|
1176
1212
|
};
|
|
1177
1213
|
const unknown = intent?.status === "running" && (!receipt || receipt.status === "uncertain");
|
|
1178
|
-
return { context: { content:
|
|
1214
|
+
return { context: { content: canonical6({
|
|
1179
1215
|
status: unknown ? "uncertain" : "not_dispatched",
|
|
1180
1216
|
reason: unknown ? "effect_outcome_unknown" : current.snapshot.reason ?? "run_ended"
|
|
1181
1217
|
}) }, isError: true };
|
|
@@ -1209,9 +1245,9 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1209
1245
|
invariant3(head, "run_not_found");
|
|
1210
1246
|
view = projectNativeRunObservation(read(key));
|
|
1211
1247
|
db.prepare(`INSERT INTO native_run_observations VALUES (?,?)
|
|
1212
|
-
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key,
|
|
1248
|
+
ON CONFLICT(run_key) DO UPDATE SET data=excluded.data`).run(key, canonical6(view));
|
|
1213
1249
|
}
|
|
1214
|
-
invariant3(
|
|
1250
|
+
invariant3(canonical6(view.snapshot.scope) === canonical6(scope) && view.snapshot.runId === runId && view.snapshot.sessionId === head.sessionId, "observation_identity_mismatch");
|
|
1215
1251
|
view.lease = head.lease === null ? null : parseNativeJson2(head.lease);
|
|
1216
1252
|
view.fence = head.fence;
|
|
1217
1253
|
view.projections = parseNativeJson2(head.projections);
|
|
@@ -1238,7 +1274,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1238
1274
|
OR json_extract(v.data,'$.snapshot.configDigest')<>json_extract(r.data,'$.snapshot.configDigest')
|
|
1239
1275
|
OR json_extract(v.data,'$.snapshot.scope')<>json_extract(r.data,'$.snapshot.scope')
|
|
1240
1276
|
OR json_extract(v.data,'$.snapshot.sessionId')<>json_extract(r.data,'$.snapshot.sessionId')
|
|
1241
|
-
OR json_extract(v.data,'$.snapshot.runId')<>json_extract(r.data,'$.snapshot.runId'))`).all(
|
|
1277
|
+
OR json_extract(v.data,'$.snapshot.runId')<>json_extract(r.data,'$.snapshot.runId'))`).all(canonical6(scope), sessionId, NATIVE_RUN_OBSERVATION, NATIVE_COMMIT_PROJECTION);
|
|
1242
1278
|
for (const { runId } of missing) this.observation(scope, runId);
|
|
1243
1279
|
return db.prepare(`SELECT json_extract(v.data,'$.snapshot.runId') AS runId,
|
|
1244
1280
|
json_extract(v.data,'$.snapshot.turnId') AS turnId, json_extract(c.value,'$.callId') AS callId,
|
|
@@ -1250,7 +1286,7 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1250
1286
|
AND json_extract(v.data,'$.snapshot.sessionId')=json_extract(r.data,'$.snapshot.sessionId')
|
|
1251
1287
|
AND json_extract(v.data,'$.snapshot.runId')=json_extract(r.data,'$.snapshot.runId')
|
|
1252
1288
|
AND json_extract(c.value,'$.status') IN ('uncertain','not_dispatched')
|
|
1253
|
-
ORDER BY r.rowid,callId`).all(
|
|
1289
|
+
ORDER BY r.rowid,callId`).all(canonical6(scope), sessionId).map((row) => ({ ...row }));
|
|
1254
1290
|
};
|
|
1255
1291
|
this.uncertainToolCalls = (scope, sessionId) => this.sessionToolOutcomes(scope, sessionId).filter((row) => row.status === "uncertain").map(({ status, ...row }) => row);
|
|
1256
1292
|
this.listScopes = (principal) => {
|
|
@@ -1613,7 +1649,7 @@ async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTimeoutMs,
|
|
|
1613
1649
|
|
|
1614
1650
|
// packages/agentkit-harness-node/src/native/model-replay.mjs
|
|
1615
1651
|
import { createHash as createHash4 } from "node:crypto";
|
|
1616
|
-
import { canonical as
|
|
1652
|
+
import { canonical as canonical7, modelWireToolCall } from "@kingsoftcloud/agentkit-harness-core";
|
|
1617
1653
|
var SEALED_KINDS = /* @__PURE__ */ new Set(["tool_calls", "final_candidate", "output_limit"]);
|
|
1618
1654
|
function profileFingerprint(profile) {
|
|
1619
1655
|
return `${String(profile?.profileId ?? "")}\0${String(profile?.profileVersion ?? "")}\0${String(profile?.compatibilityDigest ?? "")}`;
|
|
@@ -1671,7 +1707,7 @@ function anthropicReplayContent(message, profile) {
|
|
|
1671
1707
|
if (!validateReplayPairing(blocks, message)) return null;
|
|
1672
1708
|
const view = message.providerReplayProjection;
|
|
1673
1709
|
if (view) {
|
|
1674
|
-
const contentDigest = createHash4("sha256").update(
|
|
1710
|
+
const contentDigest = createHash4("sha256").update(canonical7(replay.anthropicContent)).digest("hex");
|
|
1675
1711
|
if (profile.providerReplayProjectionPolicy !== "anthropic-client-compaction/v1" || view.version !== "anthropic-client-compaction/v1" || view.profileDigest !== profile.compatibilityDigest || view.originalContentDigest !== contentDigest || !/^[0-9a-f]{64}$/.test(view.prefixDigest))
|
|
1676
1712
|
throw new ProtocolError("anthropic_replay_projection_mismatch");
|
|
1677
1713
|
blocks = blocks.filter((block) => !["thinking", "redacted_thinking"].includes(block?.type));
|
|
@@ -2012,21 +2048,28 @@ function applyAnthropicThinking(payload, profile, binding) {
|
|
|
2012
2048
|
}
|
|
2013
2049
|
function resolveProviderCompatibility(policy, binding) {
|
|
2014
2050
|
if (!policy) return null;
|
|
2015
|
-
if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
|
|
2051
|
+
if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
|
|
2016
2052
|
const rule = resolveCompatibilityRule(policy.rule, binding);
|
|
2017
2053
|
const name = String(binding.model ?? "").trim().toLowerCase();
|
|
2018
2054
|
const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
|
|
2019
|
-
const
|
|
2055
|
+
const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
|
|
2056
|
+
const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
|
|
2020
2057
|
const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
|
|
2021
2058
|
return {
|
|
2022
2059
|
rule,
|
|
2023
2060
|
supportsUsage: !strict.has(rule),
|
|
2024
2061
|
supportsThinking: !strict.has(rule) && !kimi,
|
|
2025
|
-
supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
|
|
2062
|
+
supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
|
|
2026
2063
|
reasoningRequired,
|
|
2027
|
-
modern
|
|
2064
|
+
modern,
|
|
2065
|
+
// This route already uses the supported non-thinking mode for tool work.
|
|
2066
|
+
// A bounded summary has no tools: omitting the switch can instead select
|
|
2067
|
+
// the provider's default high reasoning and consume its whole output cap.
|
|
2068
|
+
// Freeze this purpose-specific default only on new admissions; mandatory
|
|
2069
|
+
// thinking models and explicit caller choices remain authoritative.
|
|
2070
|
+
compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
|
|
2028
2071
|
// Only the observed provider/model dialects may seal without [DONE].
|
|
2029
|
-
finishOnEof:
|
|
2072
|
+
finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
|
|
2030
2073
|
supportsEffort: !kimi,
|
|
2031
2074
|
toolThinkingOff: ["zai", "kspmas-gateway"].includes(rule) && !kimi,
|
|
2032
2075
|
thinkingBudget: rule === "zai" && !kimi && !disabledEfforts ? 32e3 : null,
|
|
@@ -2081,11 +2124,12 @@ function applyProviderChatCompatibility(payload, request, binding) {
|
|
|
2081
2124
|
if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
|
|
2082
2125
|
const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
|
|
2083
2126
|
const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
|
|
2127
|
+
const boundedSummaryOff = request.purpose === "compaction" && compat.compactionThinkingOff && requested === null && mode === void 0;
|
|
2084
2128
|
const budget = result.max_completion_tokens ?? result.max_tokens;
|
|
2085
2129
|
if (mode === "enabled") {
|
|
2086
2130
|
if (!compat.supportsThinking) throw new ProtocolError("model_thinking_mode_unsupported");
|
|
2087
2131
|
result.thinking = { type: "enabled" };
|
|
2088
|
-
} else if (mayDisable && (mode === "disabled" || summaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
|
|
2132
|
+
} else if (mayDisable && (mode === "disabled" || summaryOff || boundedSummaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
|
|
2089
2133
|
if (!compat.supportsThinking) delete result.thinking;
|
|
2090
2134
|
if (!compat.supportsEffort) delete result.reasoning_effort;
|
|
2091
2135
|
if (compat.modern && ["moonshot", "kspmas-gateway"].includes(compat.rule) && result.tools) {
|
|
@@ -2122,6 +2166,80 @@ function explicitLiteralTypes(schema) {
|
|
|
2122
2166
|
return result;
|
|
2123
2167
|
}
|
|
2124
2168
|
|
|
2169
|
+
// packages/agentkit-harness-node/src/native/model-provider-error.mjs
|
|
2170
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
2171
|
+
import { canonical as canonical8, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from "@kingsoftcloud/agentkit-harness-core";
|
|
2172
|
+
var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2173
|
+
"rate_limit_error",
|
|
2174
|
+
"rate_limit_exceeded",
|
|
2175
|
+
"overloaded_error",
|
|
2176
|
+
"server_error",
|
|
2177
|
+
"api_error",
|
|
2178
|
+
"service_unavailable_error",
|
|
2179
|
+
"server_is_overloaded",
|
|
2180
|
+
"timeout_error",
|
|
2181
|
+
"MODEL_PROVIDER_RATE_LIMIT",
|
|
2182
|
+
"MODEL_PROVIDER_UNAVAILABLE"
|
|
2183
|
+
]);
|
|
2184
|
+
var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2185
|
+
"invalid_request_error",
|
|
2186
|
+
"invalid_api_key",
|
|
2187
|
+
"authentication_error",
|
|
2188
|
+
"permission_error",
|
|
2189
|
+
"not_found_error",
|
|
2190
|
+
"request_too_large",
|
|
2191
|
+
"billing_error",
|
|
2192
|
+
"insufficient_quota",
|
|
2193
|
+
"MODEL_PROVIDER_AUTHENTICATION",
|
|
2194
|
+
"MODEL_PROVIDER_PERMISSION",
|
|
2195
|
+
"MODEL_PROVIDER_INVALID_REQUEST",
|
|
2196
|
+
"MODEL_PROVIDER_NOT_FOUND",
|
|
2197
|
+
"MODEL_PROVIDER_QUOTA_EXHAUSTED"
|
|
2198
|
+
]);
|
|
2199
|
+
function classifyOpenAIProviderError(error) {
|
|
2200
|
+
const decision = classifyError(error);
|
|
2201
|
+
let fingerprint;
|
|
2202
|
+
try {
|
|
2203
|
+
fingerprint = `sha256:${createHash6("sha256").update(canonical8(error)).digest("hex")}`;
|
|
2204
|
+
} catch {
|
|
2205
|
+
return decision;
|
|
2206
|
+
}
|
|
2207
|
+
const object2 = error && typeof error === "object" && !Array.isArray(error) ? error : {};
|
|
2208
|
+
return { ...decision, diagnostic: {
|
|
2209
|
+
category: decision.failureKind,
|
|
2210
|
+
fingerprint,
|
|
2211
|
+
...MODEL_PROVIDER_ERROR_CODES.includes(object2.code) ? { code: object2.code } : {},
|
|
2212
|
+
...MODEL_PROVIDER_ERROR_TYPES.includes(object2.type) ? { type: object2.type } : {},
|
|
2213
|
+
...Number.isInteger(object2.code) && object2.code >= 400 && object2.code <= 599 ? { status: object2.code } : {}
|
|
2214
|
+
} };
|
|
2215
|
+
}
|
|
2216
|
+
function classifyError(error) {
|
|
2217
|
+
const invalid = { kind: "provider_terminal_error", failureKind: "invalid_response" };
|
|
2218
|
+
if (!error || typeof error !== "object" || Array.isArray(error)) return invalid;
|
|
2219
|
+
if (error.type != null && typeof error.type !== "string") return invalid;
|
|
2220
|
+
const status = typeof error.code === "number" ? error.code : null;
|
|
2221
|
+
if (status != null && (!Number.isInteger(status) || status < 400 || status > 599)) return invalid;
|
|
2222
|
+
const codes = [status == null ? error.code : null, error.type].filter((value) => value != null);
|
|
2223
|
+
if (codes.some((value) => typeof value !== "string")) return invalid;
|
|
2224
|
+
if (codes.some((value) => TERMINAL_ERROR_CODES.has(value))) {
|
|
2225
|
+
return { kind: "provider_terminal_error", failureKind: "client_error" };
|
|
2226
|
+
}
|
|
2227
|
+
if (status != null) {
|
|
2228
|
+
if (status === 408) return { kind: "provider_retryable_error", failureKind: "request_timeout" };
|
|
2229
|
+
if (status === 429) return { kind: "provider_retryable_error", failureKind: "rate_limit" };
|
|
2230
|
+
return {
|
|
2231
|
+
kind: status >= 500 ? "provider_retryable_error" : "provider_terminal_error",
|
|
2232
|
+
failureKind: status >= 500 ? "server_error" : "client_error"
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
const code = codes.find((value) => RETRYABLE_ERROR_CODES.has(value));
|
|
2236
|
+
if (code) return {
|
|
2237
|
+
kind: "provider_retryable_error",
|
|
2238
|
+
failureKind: ["rate_limit_error", "rate_limit_exceeded", "MODEL_PROVIDER_RATE_LIMIT"].includes(code) ? "rate_limit" : code === "timeout_error" ? "request_timeout" : "server_error"
|
|
2239
|
+
};
|
|
2240
|
+
return invalid;
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2125
2243
|
// packages/agentkit-harness-node/src/native/model-chat-usage.mjs
|
|
2126
2244
|
var CUMULATIVE_CHAT_USAGE = "cumulative-snapshots/v1";
|
|
2127
2245
|
var fields = ["inputTokens", "outputTokens", "cachedInputTokens", "reasoningTokens"];
|
|
@@ -2313,7 +2431,14 @@ function parseOpenAIBuffered(bodyText, request, { captureReplay = false, binding
|
|
|
2313
2431
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
2314
2432
|
throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
2315
2433
|
}
|
|
2316
|
-
if ("error" in payload)
|
|
2434
|
+
if ("error" in payload) {
|
|
2435
|
+
if (payload.choices != null && (!Array.isArray(payload.choices) || payload.choices.length)) {
|
|
2436
|
+
throw new ProtocolError("conflicting error envelope", "envelope_invalid");
|
|
2437
|
+
}
|
|
2438
|
+
throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
|
|
2439
|
+
streamError: classifyOpenAIProviderError(payload.error)
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2317
2442
|
const choices = payload.choices;
|
|
2318
2443
|
if (!Array.isArray(choices) || choices.length > 1) {
|
|
2319
2444
|
throw new ProtocolError("expected one completion choice", "choice_invalid");
|
|
@@ -2489,7 +2614,14 @@ function createOpenAIStreamTurn(profile, binding) {
|
|
|
2489
2614
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
2490
2615
|
throw new ProtocolError("invalid stream envelope", "envelope_invalid");
|
|
2491
2616
|
}
|
|
2492
|
-
if ("error" in payload)
|
|
2617
|
+
if ("error" in payload) {
|
|
2618
|
+
if (payload.choices != null && (!Array.isArray(payload.choices) || payload.choices.length)) {
|
|
2619
|
+
throw new ProtocolError("conflicting error envelope", "envelope_invalid");
|
|
2620
|
+
}
|
|
2621
|
+
throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
|
|
2622
|
+
streamError: classifyOpenAIProviderError(payload.error)
|
|
2623
|
+
});
|
|
2624
|
+
}
|
|
2493
2625
|
if (payload.id != null) {
|
|
2494
2626
|
if (typeof payload.id !== "string" || !payload.id) throw new ProtocolError("invalid completion ID", "identity_conflict");
|
|
2495
2627
|
if (this.completionId != null && payload.id !== this.completionId) {
|
|
@@ -2944,7 +3076,7 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
|
|
|
2944
3076
|
if (profile.providerReplayProjectionPolicy === "anthropic-client-compaction/v1") {
|
|
2945
3077
|
const originals = message.providerReplay.anthropicContent.filter((block) => block?.type === "tool_use");
|
|
2946
3078
|
for (const [index, block] of originals.entries()) wireIds.set(message.toolCalls[index].callId, block.id);
|
|
2947
|
-
const inverse = new Map([...wireIds].map(([
|
|
3079
|
+
const inverse = new Map([...wireIds].map(([canonical10, original]) => [canonical10, original]));
|
|
2948
3080
|
blocks = replayContent.map((block) => block?.type === "tool_use" ? { ...block, id: inverse.get(block.id) ?? block.id } : block);
|
|
2949
3081
|
} else blocks = replayContent;
|
|
2950
3082
|
} else {
|
|
@@ -3005,8 +3137,13 @@ function parseAnthropicBuffered(bodyText, request, { captureReplay = false, onTh
|
|
|
3005
3137
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
3006
3138
|
throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
3007
3139
|
}
|
|
3140
|
+
if ("error" in payload) {
|
|
3141
|
+
if (payload.type !== "error") throw new ProtocolError("conflicting error envelope", "envelope_invalid");
|
|
3142
|
+
throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
|
|
3143
|
+
streamError: classifyAnthropicStreamError(payload.error)
|
|
3144
|
+
});
|
|
3145
|
+
}
|
|
3008
3146
|
if ("type" in payload && payload.type !== "message") throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
3009
|
-
if ("error" in payload) throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
3010
3147
|
if (typeof payload.stop_sequence !== "undefined" && payload.stop_sequence !== null && typeof payload.stop_sequence !== "string") {
|
|
3011
3148
|
throw new ProtocolError("invalid stop_sequence");
|
|
3012
3149
|
}
|
|
@@ -3500,33 +3637,6 @@ var HOSTED_ITEM_TYPES = /* @__PURE__ */ new Set([
|
|
|
3500
3637
|
"mcp_call",
|
|
3501
3638
|
"local_shell_call"
|
|
3502
3639
|
]);
|
|
3503
|
-
var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
3504
|
-
"rate_limit_error",
|
|
3505
|
-
"rate_limit_exceeded",
|
|
3506
|
-
"overloaded_error",
|
|
3507
|
-
"server_error",
|
|
3508
|
-
"api_error",
|
|
3509
|
-
"service_unavailable_error",
|
|
3510
|
-
"server_is_overloaded",
|
|
3511
|
-
"timeout_error",
|
|
3512
|
-
"MODEL_PROVIDER_RATE_LIMIT",
|
|
3513
|
-
"MODEL_PROVIDER_UNAVAILABLE"
|
|
3514
|
-
]);
|
|
3515
|
-
var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
3516
|
-
"invalid_request_error",
|
|
3517
|
-
"invalid_api_key",
|
|
3518
|
-
"authentication_error",
|
|
3519
|
-
"permission_error",
|
|
3520
|
-
"not_found_error",
|
|
3521
|
-
"request_too_large",
|
|
3522
|
-
"billing_error",
|
|
3523
|
-
"insufficient_quota",
|
|
3524
|
-
"MODEL_PROVIDER_AUTHENTICATION",
|
|
3525
|
-
"MODEL_PROVIDER_PERMISSION",
|
|
3526
|
-
"MODEL_PROVIDER_INVALID_REQUEST",
|
|
3527
|
-
"MODEL_PROVIDER_NOT_FOUND",
|
|
3528
|
-
"MODEL_PROVIDER_QUOTA_EXHAUSTED"
|
|
3529
|
-
]);
|
|
3530
3640
|
function securityHeaders3() {
|
|
3531
3641
|
return /* @__PURE__ */ new Set(["authorization", "x-api-key", "anthropic-version", "content-type", "accept"]);
|
|
3532
3642
|
}
|
|
@@ -3787,9 +3897,9 @@ function projectResponsesOutput(payload, { status }) {
|
|
|
3787
3897
|
reasoning.push(partsText(item.content, /* @__PURE__ */ new Set(["reasoning_text", "text"])));
|
|
3788
3898
|
}
|
|
3789
3899
|
}
|
|
3790
|
-
const
|
|
3900
|
+
const canonical10 = messages.join("");
|
|
3791
3901
|
const convenience = optionalText(payload.output_text);
|
|
3792
|
-
if ("output" in payload && payload.output_text != null &&
|
|
3902
|
+
if ("output" in payload && payload.output_text != null && canonical10 !== convenience) {
|
|
3793
3903
|
throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
3794
3904
|
}
|
|
3795
3905
|
let finish;
|
|
@@ -3809,7 +3919,7 @@ function projectResponsesOutput(payload, { status }) {
|
|
|
3809
3919
|
finish = "content_filter";
|
|
3810
3920
|
calls.length = 0;
|
|
3811
3921
|
}
|
|
3812
|
-
return { finish, content:
|
|
3922
|
+
return { finish, content: canonical10 || convenience, reasoning: reasoning.join(""), calls, refused };
|
|
3813
3923
|
}
|
|
3814
3924
|
function responseMessageContent(value) {
|
|
3815
3925
|
if (!Array.isArray(value)) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
@@ -3849,8 +3959,13 @@ function parseResponsesBuffered(bodyText, request, { captureReplay = false, onTh
|
|
|
3849
3959
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
3850
3960
|
throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
3851
3961
|
}
|
|
3962
|
+
if (payload.error != null || payload.status === "failed") {
|
|
3963
|
+
if (payload.status != null && payload.status !== "failed") throw new ProtocolError("conflicting response envelope", "envelope_invalid");
|
|
3964
|
+
throw Object.assign(new ProtocolError("provider rejected generation", "provider_error"), {
|
|
3965
|
+
streamError: classifyOpenAIProviderError(payload.error)
|
|
3966
|
+
});
|
|
3967
|
+
}
|
|
3852
3968
|
const status = identityOf(payload.status);
|
|
3853
|
-
if (payload.error != null) throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
3854
3969
|
if (status === "failed") throw new ProtocolError("invalid response envelope", "envelope_invalid");
|
|
3855
3970
|
validateBufferedIdentity(payload);
|
|
3856
3971
|
const reportedUsage = parseResponsesUsage(payload.usage);
|
|
@@ -4383,21 +4498,7 @@ function createResponsesStreamState(profile) {
|
|
|
4383
4498
|
}
|
|
4384
4499
|
const usage = parseResponsesUsage(failedBody.usage);
|
|
4385
4500
|
if (usage != null) this.usage = usage;
|
|
4386
|
-
|
|
4387
|
-
const code = String(errorObj.code || errorObj.type || "");
|
|
4388
|
-
let kind;
|
|
4389
|
-
let failureKind;
|
|
4390
|
-
if (RETRYABLE_ERROR_CODES.has(code)) {
|
|
4391
|
-
kind = "provider_retryable_error";
|
|
4392
|
-
failureKind = code === "rate_limit_error" || code === "rate_limit_exceeded" ? "rate_limit" : "server_error";
|
|
4393
|
-
} else if (TERMINAL_ERROR_CODES.has(code)) {
|
|
4394
|
-
kind = "provider_terminal_error";
|
|
4395
|
-
failureKind = "client_error";
|
|
4396
|
-
} else {
|
|
4397
|
-
kind = "provider_terminal_error";
|
|
4398
|
-
failureKind = "invalid_response";
|
|
4399
|
-
}
|
|
4400
|
-
this.streamError = { kind, failureKind };
|
|
4501
|
+
this.streamError = classifyOpenAIProviderError(failedBody.error);
|
|
4401
4502
|
},
|
|
4402
4503
|
handleTerminal(event, { text: drainText, reasoning: drainReasoning }, emit) {
|
|
4403
4504
|
const responsePayload = objectOf(event.response);
|
|
@@ -4494,6 +4595,9 @@ function createResponsesStreamState(profile) {
|
|
|
4494
4595
|
const { usage, usageReported } = sealUsage(this.usage);
|
|
4495
4596
|
const reasoning = this.reasoning;
|
|
4496
4597
|
if (this.streamError) {
|
|
4598
|
+
if (this.streamError.kind === "provider_retryable_error" && (this.refused || this.finish === "content_filter")) {
|
|
4599
|
+
return { kind: "policy_abort", text: this.text, toolCalls: [], usage, usageReported };
|
|
4600
|
+
}
|
|
4497
4601
|
return {
|
|
4498
4602
|
kind: this.streamError.kind,
|
|
4499
4603
|
text: this.text,
|
|
@@ -4752,14 +4856,15 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4752
4856
|
const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
|
|
4753
4857
|
const abort = (reason) => internal.abort(reason);
|
|
4754
4858
|
let frameIndex = -1;
|
|
4755
|
-
const failed = (result2, code) => withFailure(
|
|
4859
|
+
const failed = (result2, code, fields2 = {}) => withFailure(
|
|
4756
4860
|
result2,
|
|
4757
4861
|
binding,
|
|
4758
4862
|
"stream",
|
|
4759
4863
|
code,
|
|
4760
4864
|
{
|
|
4761
4865
|
...frameIndex < 0 ? {} : { frameIndex },
|
|
4762
|
-
...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {}
|
|
4866
|
+
...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {},
|
|
4867
|
+
...fields2
|
|
4763
4868
|
}
|
|
4764
4869
|
);
|
|
4765
4870
|
try {
|
|
@@ -4781,7 +4886,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4781
4886
|
}
|
|
4782
4887
|
if (error instanceof ProtocolError) {
|
|
4783
4888
|
if (error.streamError) {
|
|
4784
|
-
return failed(
|
|
4889
|
+
return failed(
|
|
4890
|
+
state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }),
|
|
4891
|
+
"provider_error",
|
|
4892
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
|
|
4893
|
+
);
|
|
4785
4894
|
}
|
|
4786
4895
|
return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
|
|
4787
4896
|
}
|
|
@@ -4791,7 +4900,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4791
4900
|
return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: sanitizeFailureKind(error, "network_error") }), "transport_error");
|
|
4792
4901
|
}
|
|
4793
4902
|
const result = state.finalize();
|
|
4794
|
-
return failed(
|
|
4903
|
+
return failed(
|
|
4904
|
+
result,
|
|
4905
|
+
state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid",
|
|
4906
|
+
state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {}
|
|
4907
|
+
);
|
|
4795
4908
|
}
|
|
4796
4909
|
async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
|
|
4797
4910
|
const bodyText = await readBoundedText(response, maxBytes, observation.bytes);
|
|
@@ -4808,6 +4921,16 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
4808
4921
|
}
|
|
4809
4922
|
return withFailure(parseOpenAIBuffered(bodyText, request, { captureReplay, binding, onThinking }), binding, "buffered", "protocol_invalid");
|
|
4810
4923
|
} catch (error) {
|
|
4924
|
+
if (error instanceof ProtocolError && error.streamError) {
|
|
4925
|
+
const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
|
|
4926
|
+
return withFailure(
|
|
4927
|
+
result,
|
|
4928
|
+
binding,
|
|
4929
|
+
"buffered",
|
|
4930
|
+
"provider_error",
|
|
4931
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
|
|
4932
|
+
);
|
|
4933
|
+
}
|
|
4811
4934
|
return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
|
|
4812
4935
|
}
|
|
4813
4936
|
}
|
|
@@ -4852,7 +4975,7 @@ function protocolCode(error) {
|
|
|
4852
4975
|
function withFailure(result, binding, phase, code, fields2 = {}) {
|
|
4853
4976
|
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
|
|
4854
4977
|
const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
|
|
4855
|
-
return { ...result, failureDiagnostic: { contract: fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
|
|
4978
|
+
return { ...result, failureDiagnostic: { contract: fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
|
|
4856
4979
|
}
|
|
4857
4980
|
function retryableResult(failureKind, retryAfterMs = null) {
|
|
4858
4981
|
const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
|
@@ -4913,7 +5036,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
4913
5036
|
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
4914
5037
|
import { mkdirSync as mkdirSync2 } from "node:fs";
|
|
4915
5038
|
import { dirname as dirname2 } from "node:path";
|
|
4916
|
-
import { createHash as
|
|
5039
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
4917
5040
|
function stable(value) {
|
|
4918
5041
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
4919
5042
|
if (Array.isArray(value)) return "[" + value.map(stable).join(",") + "]";
|
|
@@ -4921,7 +5044,7 @@ function stable(value) {
|
|
|
4921
5044
|
return "{" + keys.map((k) => JSON.stringify(k) + ":" + stable(value[k])).join(",") + "}";
|
|
4922
5045
|
}
|
|
4923
5046
|
function digestRequest(method, params) {
|
|
4924
|
-
return
|
|
5047
|
+
return createHash7("sha256").update(stable({ method, params: params ?? null })).digest("hex");
|
|
4925
5048
|
}
|
|
4926
5049
|
var RpcRequestLedger = class {
|
|
4927
5050
|
constructor(filename, { now = Date.now } = {}) {
|
|
@@ -5195,8 +5318,8 @@ var ERR = {
|
|
|
5195
5318
|
var success = (id, result) => ({ jsonrpc: "2.0", id, result });
|
|
5196
5319
|
var errorResponse = (id, e, data) => ({ jsonrpc: "2.0", id, error: publicFailureContent({ code: e.code, message: e.message, ...data ? { data } : {} }) });
|
|
5197
5320
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
5198
|
-
var digest = (value) =>
|
|
5199
|
-
var runIdFor = (requestId) => "rpc:" +
|
|
5321
|
+
var digest = (value) => createHash8("sha256").update(canonical9(value)).digest("hex");
|
|
5322
|
+
var runIdFor = (requestId) => "rpc:" + createHash8("sha256").update(requestId).digest("hex");
|
|
5200
5323
|
function nativeErrorToRpc(e) {
|
|
5201
5324
|
if (isNativeError(e)) {
|
|
5202
5325
|
if (e.code === "run_not_found") return ERR.run_not_found;
|