maka-agent 0.2.0-dev.32.20260914 → 0.2.0-dev.35.20260915
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/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@maka/eval/dist/metering-checkpoint.js +4 -4
- package/node_modules/@maka/eval/harbor/relay_agent.py +1 -2
- package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +2 -18
- package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +1 -2
- package/node_modules/@maka/runtime/dist/provider-error-classification.js +29 -38
- package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +4 -1
- package/node_modules/@maka/runtime-host/dist/client/wait-for-ready.js +1 -1
- package/node_modules/@maka/runtime-host/dist/control/endpoint.js +7 -6
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +2 -2
- package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +1 -0
- package/node_modules/@maka/storage/dist/agent-run-store-contract.js +942 -0
- package/node_modules/@maka/storage/dist/agent-run-store.js +3 -923
- package/node_modules/@maka/storage/dist/artifact-store.js +63 -7
- package/node_modules/@maka/storage/dist/execution-persistence-provider.js +54 -0
- package/node_modules/@maka/storage/dist/execution-stores.js +181 -58
- package/node_modules/@maka/storage/dist/goal-authority.js +39 -8
- package/node_modules/@maka/storage/dist/graph-control-values.js +126 -0
- package/node_modules/@maka/storage/dist/interaction-store-contract.js +231 -0
- package/node_modules/@maka/storage/dist/interaction-store.js +62 -217
- package/node_modules/@maka/storage/dist/local-execution-persistence.js +80 -0
- package/node_modules/@maka/storage/dist/root-authority.js +4 -0
- package/node_modules/@maka/storage/dist/runtime-event-store-contract.js +19 -0
- package/node_modules/@maka/storage/dist/runtime-partial-values.js +114 -0
- package/node_modules/@maka/storage/dist/session-store-contract.js +61 -0
- package/node_modules/@maka/storage/dist/session-store-values.js +342 -0
- package/node_modules/@maka/storage/dist/session-store.js +7 -351
- package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +4 -185
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +9 -129
- package/node_modules/@maka/storage/dist/storage-writer-composition.js +2 -3
- package/node_modules/@maka/storage/dist/tool-commit-validation.js +111 -0
- package/node_modules/@maka/storage/package.json +1 -0
- package/package.json +1 -1
|
@@ -19,27 +19,14 @@
|
|
|
19
19
|
import { resolve } from 'node:path';
|
|
20
20
|
import { isDeepStrictEqual } from 'node:util';
|
|
21
21
|
import { decodeAgentRunEvent, decodeRuntimeEvent } from './execution-record-codec.js';
|
|
22
|
-
import { normalizeSubmittedTurnIntent, submittedTurnIntentsEqual, } from './submitted-turn-intent.js';
|
|
23
|
-
import { assertNoReservedWorkspaceAuthorityAppend } from './runtime-event-authority.js';
|
|
24
22
|
import { acquireOperationalStateDatabase, } from './operational-state-store.js';
|
|
25
23
|
import { assertEvidenceReadBudget, measureEvidenceRows, } from './bounded-evidence.js';
|
|
26
|
-
import { decodeSkillInvocationResult, } from '@maka/core/skill-invocation';
|
|
27
|
-
import { aggregateMessageContents, decodeMessageContent, hasMeaningfulMessageContent, isCanonicalAttachmentRef, messageContentsEqual, } from '@maka/core/events';
|
|
28
|
-
import { decodeAgentGraphIntentClaim } from '@maka/core/agent-graph-control';
|
|
29
|
-
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENT_COUNT } from '@maka/core/attachments';
|
|
30
24
|
import { MODEL_CALL_ATTEMPT_EVENT_TYPE } from '@maka/core/model-call-attempt';
|
|
31
25
|
import { LATEST_CONTEXT_PROJECTION_TYPE, RUN_COMPOSITION_RECORDED_EVENT_TYPE, supersedesLatestContext, } from '@maka/core/agent-run';
|
|
32
|
-
import { isSessionInlineInvocation
|
|
26
|
+
import { isSessionInlineInvocation } from '@maka/core/runtime-invocation';
|
|
33
27
|
import { decodeRuntimeInvocationOpened, runtimeEventInvocationOpening, } from '@maka/core/runtime-event';
|
|
34
|
-
import {
|
|
35
|
-
|
|
36
|
-
import { validateGenericToolLedgerAppend, } from '@maka/core/tool-ledger-scanner';
|
|
37
|
-
const SAFE_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
38
|
-
export const ROOT_TURN_ADMISSION_SCHEMA_VERSION = 1;
|
|
39
|
-
export const ROOT_TURN_ADMISSION_MAX_SOURCE_MESSAGES = 64;
|
|
40
|
-
export const ROOT_TURN_ADMISSION_MAX_CONTENT_BYTES = 64 * 1024;
|
|
41
|
-
export const ROOT_TURN_ADMISSION_MAX_RECORD_BYTES = 1024 * 1024;
|
|
42
|
-
const ROOT_TURN_ADMISSION_MAX_AGGREGATED_ATTACHMENTS = ROOT_TURN_ADMISSION_MAX_SOURCE_MESSAGES * MAX_ATTACHMENT_COUNT;
|
|
28
|
+
import { normalizeRootTurnStartRejection, normalizeStoredRootTurnStartRejection, normalizeAdmitRootTurnInput, shouldPreserveCheckpointProjectionDuringAppend, shouldPreserveProjectionDuringRepair, isProjectedAgentRunEvent, assertSafeId, normalizeRootTurnAdmission, orderRootTurnAdmissionChain, rootTurnAdmissionPayloadsEqual, sanitizeJson, } from './agent-run-store-contract.js';
|
|
29
|
+
export { ROOT_TURN_ADMISSION_SCHEMA_VERSION, ROOT_TURN_ADMISSION_MAX_SOURCE_MESSAGES, ROOT_TURN_ADMISSION_MAX_CONTENT_BYTES, ROOT_TURN_ADMISSION_MAX_RECORD_BYTES, rootTurnAdmissionRecordFits, normalizeRootTurnAdmissionPayload, } from './agent-run-store-contract.js';
|
|
43
30
|
class RuntimeEventPostEffectError extends Error {
|
|
44
31
|
cause;
|
|
45
32
|
name = 'RuntimeEventPostEffectError';
|
|
@@ -706,910 +693,3 @@ function readSqliteRootTurnStartRejection(db, sessionId, turnId) {
|
|
|
706
693
|
}
|
|
707
694
|
return normalizeStoredRootTurnStartRejection(JSON.parse(row.record_json), sessionId, turnId);
|
|
708
695
|
}
|
|
709
|
-
function normalizeRootTurnStartRejection(input) {
|
|
710
|
-
return normalizeStoredRootTurnStartRejection({
|
|
711
|
-
schemaVersion: 1,
|
|
712
|
-
sessionId: input.sessionId,
|
|
713
|
-
turnId: input.turnId,
|
|
714
|
-
execution: input.execution,
|
|
715
|
-
skillInvocation: input.skillInvocation,
|
|
716
|
-
rejectedAt: input.rejectedAt,
|
|
717
|
-
}, input.sessionId, input.turnId);
|
|
718
|
-
}
|
|
719
|
-
function normalizeStoredRootTurnStartRejection(value, sessionId, turnId) {
|
|
720
|
-
assertSafeId(sessionId, 'Invalid session id');
|
|
721
|
-
assertSafeId(turnId, 'Invalid turn id');
|
|
722
|
-
if (!isPlainRecord(value) ||
|
|
723
|
-
!hasExactKeys(value, [
|
|
724
|
-
'schemaVersion',
|
|
725
|
-
'sessionId',
|
|
726
|
-
'turnId',
|
|
727
|
-
'execution',
|
|
728
|
-
'skillInvocation',
|
|
729
|
-
'rejectedAt',
|
|
730
|
-
]) ||
|
|
731
|
-
value.schemaVersion !== 1 ||
|
|
732
|
-
value.sessionId !== sessionId ||
|
|
733
|
-
value.turnId !== turnId ||
|
|
734
|
-
!Number.isSafeInteger(value.rejectedAt) ||
|
|
735
|
-
value.rejectedAt < 0) {
|
|
736
|
-
throw new Error(`Invalid root Turn start rejection for turn ${turnId}`);
|
|
737
|
-
}
|
|
738
|
-
const execution = normalizeRootExecutionDescriptor(value.execution);
|
|
739
|
-
if (execution.kind !== 'external_message') {
|
|
740
|
-
throw new Error('Root Turn start rejection requires external message execution');
|
|
741
|
-
}
|
|
742
|
-
const skillInvocation = decodeSkillInvocationResult(value.skillInvocation);
|
|
743
|
-
if (skillInvocation.loaded.length !== 0 || skillInvocation.failed.length === 0) {
|
|
744
|
-
throw new Error('Root Turn start rejection requires only failed Skill invocations');
|
|
745
|
-
}
|
|
746
|
-
const rejection = {
|
|
747
|
-
schemaVersion: 1,
|
|
748
|
-
sessionId,
|
|
749
|
-
turnId,
|
|
750
|
-
execution,
|
|
751
|
-
skillInvocation,
|
|
752
|
-
rejectedAt: value.rejectedAt,
|
|
753
|
-
};
|
|
754
|
-
assertRootTurnAdmissionSerializedSize(`${JSON.stringify(rejection)}\n`);
|
|
755
|
-
Object.freeze(rejection.execution);
|
|
756
|
-
return Object.freeze(rejection);
|
|
757
|
-
}
|
|
758
|
-
function normalizeAdmitRootTurnInput(input) {
|
|
759
|
-
assertSafeId(input.sessionId, 'Invalid session id');
|
|
760
|
-
assertSafeId(input.turnId, 'Invalid turn id');
|
|
761
|
-
assertSafeId(input.proposedRunId, 'Invalid run id');
|
|
762
|
-
if (input.proposedUserMessageId !== null) {
|
|
763
|
-
assertSafeId(input.proposedUserMessageId, 'Invalid user message id');
|
|
764
|
-
}
|
|
765
|
-
if (input.previousRootTurnId !== null) {
|
|
766
|
-
assertSafeId(input.previousRootTurnId, 'Invalid previous root turn id');
|
|
767
|
-
if (input.previousRootTurnId === input.turnId) {
|
|
768
|
-
throw new Error('Root turn admission cannot reference itself');
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
if (!Number.isSafeInteger(input.admittedAt) || input.admittedAt < 0) {
|
|
772
|
-
throw new Error('Invalid root turn admission timestamp');
|
|
773
|
-
}
|
|
774
|
-
const { normalizedInput, sourceMessages } = normalizeRootTurnAdmissionPayload(input.normalizedInput, input.sourceMessages);
|
|
775
|
-
const turnOrchestration = normalizeTurnOrchestration(input.turnOrchestration);
|
|
776
|
-
const skillInvocation = input.skillInvocation === undefined
|
|
777
|
-
? undefined
|
|
778
|
-
: decodeSkillInvocationResult(input.skillInvocation);
|
|
779
|
-
const authorization = normalizeRootTurnAdmissionAuthorization(input.authorization);
|
|
780
|
-
const execution = normalizeRootExecutionDescriptor(input.execution);
|
|
781
|
-
if (execution.kind === 'legacy_automation') {
|
|
782
|
-
throw new Error('New root admission cannot use removed Automation authority');
|
|
783
|
-
}
|
|
784
|
-
const admission = {
|
|
785
|
-
schemaVersion: ROOT_TURN_ADMISSION_SCHEMA_VERSION,
|
|
786
|
-
sessionId: input.sessionId,
|
|
787
|
-
turnId: input.turnId,
|
|
788
|
-
runId: input.proposedRunId,
|
|
789
|
-
userMessageId: input.proposedUserMessageId,
|
|
790
|
-
execution,
|
|
791
|
-
previousRootTurnId: input.previousRootTurnId,
|
|
792
|
-
normalizedInput,
|
|
793
|
-
...(turnOrchestration ? { turnOrchestration } : {}),
|
|
794
|
-
...(skillInvocation ? { skillInvocation } : {}),
|
|
795
|
-
...(authorization ? { authorization } : {}),
|
|
796
|
-
sourceMessages,
|
|
797
|
-
admittedAt: input.admittedAt,
|
|
798
|
-
};
|
|
799
|
-
assertRootTurnAdmissionContract(admission);
|
|
800
|
-
assertRootTurnAdmissionRecordSize(admission);
|
|
801
|
-
return deepFreezeRootTurnAdmission(admission);
|
|
802
|
-
}
|
|
803
|
-
/** Whether a proposed admission satisfies the complete durable record contract and size bound. */
|
|
804
|
-
export function rootTurnAdmissionRecordFits(input) {
|
|
805
|
-
try {
|
|
806
|
-
normalizeAdmitRootTurnInput(input);
|
|
807
|
-
return true;
|
|
808
|
-
}
|
|
809
|
-
catch {
|
|
810
|
-
return false;
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
function shouldPreserveCheckpointProjectionDuringAppend(current, candidate) {
|
|
814
|
-
if (!current)
|
|
815
|
-
return false;
|
|
816
|
-
const currentSourceBound = historyCompactProjectionIsSourceBound(current);
|
|
817
|
-
const candidateSourceBound = historyCompactProjectionIsSourceBound(candidate);
|
|
818
|
-
if (currentSourceBound !== candidateSourceBound)
|
|
819
|
-
return currentSourceBound;
|
|
820
|
-
const currentCoverage = historyCompactProjectionCoverage(current);
|
|
821
|
-
const candidateCoverage = historyCompactProjectionCoverage(candidate);
|
|
822
|
-
return (currentCoverage !== undefined &&
|
|
823
|
-
(candidateCoverage === undefined || currentCoverage > candidateCoverage));
|
|
824
|
-
}
|
|
825
|
-
function shouldPreserveProjectionDuringRepair(current, candidate, type) {
|
|
826
|
-
if (!current)
|
|
827
|
-
return false;
|
|
828
|
-
if (type === LATEST_CONTEXT_PROJECTION_TYPE) {
|
|
829
|
-
// Same ordering rule as the append-time guard, so repair and write cannot
|
|
830
|
-
// disagree about which request is the latest one. An incumbent whose order
|
|
831
|
-
// cannot be read is NOT preserved: the reader already treats an
|
|
832
|
-
// undecodable row as unanswered and rebuilds from the ledger, so keeping
|
|
833
|
-
// it would make that rebuild unwritable and leave every later refresh
|
|
834
|
-
// rescanning the whole session (#2323).
|
|
835
|
-
const incumbent = latestContextOrder(current);
|
|
836
|
-
if (!incumbent)
|
|
837
|
-
return false;
|
|
838
|
-
const arriving = candidate && latestContextOrder(candidate);
|
|
839
|
-
if (!arriving)
|
|
840
|
-
return true;
|
|
841
|
-
return !supersedesLatestContext(arriving, incumbent);
|
|
842
|
-
}
|
|
843
|
-
if (type !== 'history_compact_checkpoint_recorded')
|
|
844
|
-
return true;
|
|
845
|
-
const currentSourceBound = historyCompactProjectionIsSourceBound(current);
|
|
846
|
-
const candidateSourceBound = candidate ? historyCompactProjectionIsSourceBound(candidate) : false;
|
|
847
|
-
if (currentSourceBound !== candidateSourceBound)
|
|
848
|
-
return currentSourceBound;
|
|
849
|
-
const currentCoverage = historyCompactProjectionCoverage(current);
|
|
850
|
-
const candidateCoverage = candidate && historyCompactProjectionCoverage(candidate);
|
|
851
|
-
return (currentCoverage !== undefined &&
|
|
852
|
-
(candidateCoverage === null ||
|
|
853
|
-
candidateCoverage === undefined ||
|
|
854
|
-
currentCoverage >= candidateCoverage));
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* The ordering facts a stored latest-context row carries, or `undefined` when
|
|
858
|
-
* the row cannot state them — a damaged snapshot, or one written by a shape
|
|
859
|
-
* this build does not understand.
|
|
860
|
-
*/
|
|
861
|
-
function latestContextOrder(event) {
|
|
862
|
-
const data = event.data;
|
|
863
|
-
if (!data || typeof data.completedAt !== 'number' || typeof data.attemptId !== 'string') {
|
|
864
|
-
return undefined;
|
|
865
|
-
}
|
|
866
|
-
return { completedAt: data.completedAt, attemptId: data.attemptId };
|
|
867
|
-
}
|
|
868
|
-
function historyCompactProjectionIsSourceBound(event) {
|
|
869
|
-
const checkpoint = event.data?.checkpoint;
|
|
870
|
-
if (!checkpoint || typeof checkpoint !== 'object')
|
|
871
|
-
return false;
|
|
872
|
-
const source = checkpoint.source;
|
|
873
|
-
if (!source || typeof source !== 'object')
|
|
874
|
-
return false;
|
|
875
|
-
return source.kind === 'runtime_event_projection';
|
|
876
|
-
}
|
|
877
|
-
function assertNoReservedToolLedgerFact(event) {
|
|
878
|
-
assertNoReservedWorkspaceAuthorityAppend(event);
|
|
879
|
-
if (event.actions?.continuationStart !== undefined) {
|
|
880
|
-
throw new Error('Continuation start facts require SQLite continuation authority');
|
|
881
|
-
}
|
|
882
|
-
const validation = validateGenericToolLedgerAppend(event);
|
|
883
|
-
if (validation.ok)
|
|
884
|
-
return;
|
|
885
|
-
if (validation.code === 'reserved_recovery_fact') {
|
|
886
|
-
throw new Error('Tool recovery facts require the atomic recovery bundle writer');
|
|
887
|
-
}
|
|
888
|
-
if (validation.code === 'reserved_tool_boundary_fact') {
|
|
889
|
-
throw new Error('Durable tool facts require the atomic tool boundary writer');
|
|
890
|
-
}
|
|
891
|
-
throw new Error(`RuntimeEvent ${event.id} violates its semantic lane`);
|
|
892
|
-
}
|
|
893
|
-
function canonicalizeRuntimeEventForStorage(event) {
|
|
894
|
-
return encodeCanonicalRuntimeEvent(event).event;
|
|
895
|
-
}
|
|
896
|
-
function isToolLedgerBearingEvent(event) {
|
|
897
|
-
return (event.content?.kind === 'function_call' ||
|
|
898
|
-
event.content?.kind === 'function_response' ||
|
|
899
|
-
event.actions?.toolDispatch !== undefined ||
|
|
900
|
-
event.actions?.toolRecovery !== undefined);
|
|
901
|
-
}
|
|
902
|
-
function historyCompactProjectionCoverage(event) {
|
|
903
|
-
const checkpoint = event.data?.checkpoint;
|
|
904
|
-
if (!checkpoint || typeof checkpoint !== 'object')
|
|
905
|
-
return undefined;
|
|
906
|
-
const coverage = checkpoint.coverage;
|
|
907
|
-
if (!coverage || typeof coverage !== 'object')
|
|
908
|
-
return undefined;
|
|
909
|
-
const eventCount = coverage.eventCount;
|
|
910
|
-
return typeof eventCount === 'number' && Number.isSafeInteger(eventCount) && eventCount >= 0
|
|
911
|
-
? eventCount
|
|
912
|
-
: undefined;
|
|
913
|
-
}
|
|
914
|
-
function isProjectedAgentRunEvent(value, sessionId, type) {
|
|
915
|
-
if (!value || typeof value !== 'object')
|
|
916
|
-
return false;
|
|
917
|
-
const event = value;
|
|
918
|
-
return (event.type === type &&
|
|
919
|
-
event.sessionId === sessionId &&
|
|
920
|
-
typeof event.id === 'string' &&
|
|
921
|
-
typeof event.runId === 'string' &&
|
|
922
|
-
typeof event.turnId === 'string' &&
|
|
923
|
-
Number.isFinite(event.ts));
|
|
924
|
-
}
|
|
925
|
-
function assertSafeId(value, message) {
|
|
926
|
-
if (!isSafeId(value))
|
|
927
|
-
throw new Error(message);
|
|
928
|
-
}
|
|
929
|
-
function assertIdentitySearchLimit(limit) {
|
|
930
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 256) {
|
|
931
|
-
throw new RangeError('AgentRun identity search limit must be an integer between 1 and 256');
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
function isSafeId(value) {
|
|
935
|
-
return SAFE_ID_PATTERN.test(value);
|
|
936
|
-
}
|
|
937
|
-
function isGraphControlIdentity(value) {
|
|
938
|
-
return (value.length > 0 &&
|
|
939
|
-
value.length <= 256 &&
|
|
940
|
-
value.trim() === value &&
|
|
941
|
-
/^[A-Za-z0-9._:-]+$/.test(value));
|
|
942
|
-
}
|
|
943
|
-
function normalizeRootTurnAdmission(value, sessionId, turnId) {
|
|
944
|
-
if (!isPlainRecord(value)) {
|
|
945
|
-
throw new Error(`Invalid root turn admission for turn ${turnId}: expected an object`);
|
|
946
|
-
}
|
|
947
|
-
const record = value;
|
|
948
|
-
const valid = record.schemaVersion === ROOT_TURN_ADMISSION_SCHEMA_VERSION &&
|
|
949
|
-
record.sessionId === sessionId &&
|
|
950
|
-
record.turnId === turnId &&
|
|
951
|
-
typeof record.runId === 'string' &&
|
|
952
|
-
isSafeId(record.runId) &&
|
|
953
|
-
(record.userMessageId === null ||
|
|
954
|
-
(typeof record.userMessageId === 'string' && isSafeId(record.userMessageId))) &&
|
|
955
|
-
(record.previousRootTurnId === null ||
|
|
956
|
-
(typeof record.previousRootTurnId === 'string' &&
|
|
957
|
-
isSafeId(record.previousRootTurnId) &&
|
|
958
|
-
record.previousRootTurnId !== turnId)) &&
|
|
959
|
-
Number.isSafeInteger(record.admittedAt) &&
|
|
960
|
-
record.admittedAt >= 0 &&
|
|
961
|
-
hasRootTurnAdmissionKeys(record);
|
|
962
|
-
if (!valid) {
|
|
963
|
-
throw new Error(`Invalid root turn admission for turn ${turnId}: malformed fields`);
|
|
964
|
-
}
|
|
965
|
-
const { normalizedInput, sourceMessages } = normalizeRootTurnAdmissionPayload(record.normalizedInput, record.sourceMessages);
|
|
966
|
-
const turnOrchestration = normalizeTurnOrchestration(record.turnOrchestration);
|
|
967
|
-
const skillInvocation = record.skillInvocation === undefined
|
|
968
|
-
? undefined
|
|
969
|
-
: decodeSkillInvocationResult(record.skillInvocation);
|
|
970
|
-
const authorization = normalizeRootTurnAdmissionAuthorization(record.authorization);
|
|
971
|
-
const admission = {
|
|
972
|
-
schemaVersion: ROOT_TURN_ADMISSION_SCHEMA_VERSION,
|
|
973
|
-
sessionId,
|
|
974
|
-
turnId,
|
|
975
|
-
runId: record.runId,
|
|
976
|
-
userMessageId: record.userMessageId,
|
|
977
|
-
execution: normalizeRootExecutionDescriptor(record.execution),
|
|
978
|
-
previousRootTurnId: record.previousRootTurnId,
|
|
979
|
-
normalizedInput,
|
|
980
|
-
...(turnOrchestration ? { turnOrchestration } : {}),
|
|
981
|
-
...(skillInvocation ? { skillInvocation } : {}),
|
|
982
|
-
...(authorization ? { authorization } : {}),
|
|
983
|
-
sourceMessages,
|
|
984
|
-
admittedAt: record.admittedAt,
|
|
985
|
-
};
|
|
986
|
-
assertRootTurnAdmissionContract(admission);
|
|
987
|
-
assertRootTurnAdmissionRecordSize(admission);
|
|
988
|
-
return deepFreezeRootTurnAdmission(admission);
|
|
989
|
-
}
|
|
990
|
-
function decodeRootSourceMessageProofPointer(value, sessionId, messageId) {
|
|
991
|
-
if (!isPlainRecord(value) ||
|
|
992
|
-
!hasExactKeys(value, ['schemaVersion', 'sessionId', 'messageId', 'turnId']) ||
|
|
993
|
-
value.schemaVersion !== 1 ||
|
|
994
|
-
value.sessionId !== sessionId ||
|
|
995
|
-
value.messageId !== messageId ||
|
|
996
|
-
typeof value.turnId !== 'string' ||
|
|
997
|
-
!isSafeId(value.turnId)) {
|
|
998
|
-
throw new Error(`Invalid root source message proof: ${messageId}`);
|
|
999
|
-
}
|
|
1000
|
-
return Object.freeze({ turnId: value.turnId });
|
|
1001
|
-
}
|
|
1002
|
-
function orderRootTurnAdmissionChain(sessionId, admissions) {
|
|
1003
|
-
if (admissions.length === 0)
|
|
1004
|
-
return [];
|
|
1005
|
-
const byTurnId = new Map(admissions.map((admission) => [admission.turnId, admission]));
|
|
1006
|
-
if (byTurnId.size !== admissions.length) {
|
|
1007
|
-
throw new Error(`Session ${sessionId} has duplicate root turn admissions`);
|
|
1008
|
-
}
|
|
1009
|
-
for (const admission of admissions) {
|
|
1010
|
-
const predecessor = admission.previousRootTurnId;
|
|
1011
|
-
if (predecessor !== null && !byTurnId.has(predecessor)) {
|
|
1012
|
-
throw new Error(`Root turn admission ${admission.turnId} has missing predecessor ${predecessor}`);
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
const roots = admissions.filter((admission) => admission.previousRootTurnId === null);
|
|
1016
|
-
if (roots.length !== 1) {
|
|
1017
|
-
throw new Error(`Session ${sessionId} must have exactly one root turn admission root`);
|
|
1018
|
-
}
|
|
1019
|
-
const childByTurnId = new Map();
|
|
1020
|
-
for (const admission of admissions) {
|
|
1021
|
-
const predecessor = admission.previousRootTurnId;
|
|
1022
|
-
if (predecessor === null)
|
|
1023
|
-
continue;
|
|
1024
|
-
const existing = childByTurnId.get(predecessor);
|
|
1025
|
-
if (existing) {
|
|
1026
|
-
throw new Error(`Root turn admission ${predecessor} branches to ${existing.turnId} and ${admission.turnId}`);
|
|
1027
|
-
}
|
|
1028
|
-
childByTurnId.set(predecessor, admission);
|
|
1029
|
-
}
|
|
1030
|
-
const ordered = [];
|
|
1031
|
-
let current = roots[0];
|
|
1032
|
-
while (current) {
|
|
1033
|
-
ordered.push(current);
|
|
1034
|
-
current = childByTurnId.get(current.turnId);
|
|
1035
|
-
}
|
|
1036
|
-
if (ordered.length !== admissions.length) {
|
|
1037
|
-
throw new Error(`Session ${sessionId} root turn admissions do not form one linear chain`);
|
|
1038
|
-
}
|
|
1039
|
-
return ordered;
|
|
1040
|
-
}
|
|
1041
|
-
function normalizeRootTurnMessageContent(value, description, maxAttachments) {
|
|
1042
|
-
let normalized;
|
|
1043
|
-
try {
|
|
1044
|
-
normalized = decodeMessageContent(value);
|
|
1045
|
-
}
|
|
1046
|
-
catch {
|
|
1047
|
-
if (isPlainRecord(value) && Array.isArray(value.attachments)) {
|
|
1048
|
-
const invalidAttachmentIndex = value.attachments.findIndex((attachment) => !isCanonicalAttachmentRef(attachment));
|
|
1049
|
-
if (invalidAttachmentIndex >= 0) {
|
|
1050
|
-
throw new Error(`Invalid ${description} attachment at index ${invalidAttachmentIndex}`);
|
|
1051
|
-
}
|
|
1052
|
-
}
|
|
1053
|
-
throw new Error(`Invalid ${description}`);
|
|
1054
|
-
}
|
|
1055
|
-
// Quote- or attachment-only input is meaningful (#4804): the text carrier
|
|
1056
|
-
// alone no longer decides durability admission.
|
|
1057
|
-
if (!hasMeaningfulMessageContent(normalized) ||
|
|
1058
|
-
(normalized.attachments?.length ?? 0) > maxAttachments) {
|
|
1059
|
-
throw new Error(`Invalid ${description}`);
|
|
1060
|
-
}
|
|
1061
|
-
for (const [index, attachment] of (normalized.attachments ?? []).entries()) {
|
|
1062
|
-
if (!isValidRootTurnAttachment(attachment)) {
|
|
1063
|
-
throw new Error(`Invalid ${description} attachment at index ${index}`);
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
if (Buffer.byteLength(JSON.stringify(normalized), 'utf8') > ROOT_TURN_ADMISSION_MAX_CONTENT_BYTES) {
|
|
1067
|
-
throw new Error(`Invalid ${description}: content exceeds size limit`);
|
|
1068
|
-
}
|
|
1069
|
-
deepFreezeRootTurnMessageContent(normalized);
|
|
1070
|
-
return normalized;
|
|
1071
|
-
}
|
|
1072
|
-
function isValidRootTurnAttachment(attachment) {
|
|
1073
|
-
return isCanonicalAttachmentRef(attachment) && attachment.bytes <= MAX_ATTACHMENT_BYTES;
|
|
1074
|
-
}
|
|
1075
|
-
export function normalizeRootTurnAdmissionPayload(normalizedInputValue, sourceMessagesValue) {
|
|
1076
|
-
const sourceMessages = normalizeRootTurnSourceMessages(sourceMessagesValue);
|
|
1077
|
-
if (normalizedInputValue === null) {
|
|
1078
|
-
if (sourceMessages.length > 0) {
|
|
1079
|
-
throw new Error('Root turn admission without input cannot have source messages');
|
|
1080
|
-
}
|
|
1081
|
-
return { normalizedInput: null, sourceMessages };
|
|
1082
|
-
}
|
|
1083
|
-
const normalizedInputMaxAttachments = sourceMessages.length > 1
|
|
1084
|
-
? ROOT_TURN_ADMISSION_MAX_AGGREGATED_ATTACHMENTS
|
|
1085
|
-
: MAX_ATTACHMENT_COUNT;
|
|
1086
|
-
const normalizedInput = normalizeRootTurnMessageContent(normalizedInputValue, 'root turn normalized input', normalizedInputMaxAttachments);
|
|
1087
|
-
if (sourceMessages.length > 0) {
|
|
1088
|
-
const expectedInput = normalizeRootTurnMessageContent(aggregateMessageContents(sourceMessages.map((source) => source.content)), 'root turn aggregated source content', normalizedInputMaxAttachments);
|
|
1089
|
-
if (!messageContentsEqual(normalizedInput, expectedInput)) {
|
|
1090
|
-
throw new Error('Root turn admission input content does not match source messages');
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
const turnStartedCount = sourceMessages.filter((source) => source.disposition === 'turn_started').length;
|
|
1094
|
-
if (turnStartedCount > 0 && (turnStartedCount !== 1 || sourceMessages.length !== 1)) {
|
|
1095
|
-
throw new Error('Root turn admission turn_started source must be the only source message');
|
|
1096
|
-
}
|
|
1097
|
-
return { normalizedInput, sourceMessages };
|
|
1098
|
-
}
|
|
1099
|
-
function normalizeRootTurnSourceMessages(value) {
|
|
1100
|
-
if (!Array.isArray(value) || value.length > ROOT_TURN_ADMISSION_MAX_SOURCE_MESSAGES) {
|
|
1101
|
-
throw new Error('Invalid root turn source messages: expected a bounded array');
|
|
1102
|
-
}
|
|
1103
|
-
const messageIds = new Set();
|
|
1104
|
-
const normalized = value.map((item, index) => {
|
|
1105
|
-
if (!isPlainRecord(item) ||
|
|
1106
|
-
!hasExactKeys(item, [
|
|
1107
|
-
'messageId',
|
|
1108
|
-
'content',
|
|
1109
|
-
'placement',
|
|
1110
|
-
'disposition',
|
|
1111
|
-
...(Object.hasOwn(item, 'submittedContentDigest') ? ['submittedContentDigest'] : []),
|
|
1112
|
-
...(Object.hasOwn(item, 'submittedPlacement') ? ['submittedPlacement'] : []),
|
|
1113
|
-
...(Object.hasOwn(item, 'submittedIntent') ? ['submittedIntent'] : []),
|
|
1114
|
-
...(Object.hasOwn(item, 'skillInvocation') ? ['skillInvocation'] : []),
|
|
1115
|
-
])) {
|
|
1116
|
-
throw new Error(`Invalid root turn source message at index ${index}`);
|
|
1117
|
-
}
|
|
1118
|
-
const { messageId, content, submittedContentDigest, submittedPlacement, submittedIntent, skillInvocation, placement, disposition, } = item;
|
|
1119
|
-
if (typeof messageId !== 'string' ||
|
|
1120
|
-
!isSafeId(messageId) ||
|
|
1121
|
-
(placement !== 'current_turn' && placement !== 'next_turn') ||
|
|
1122
|
-
(disposition !== 'steering' &&
|
|
1123
|
-
disposition !== 'followup' &&
|
|
1124
|
-
disposition !== 'turn_started') ||
|
|
1125
|
-
(disposition === 'steering' && placement !== 'current_turn') ||
|
|
1126
|
-
(disposition === 'followup' && placement !== 'next_turn') ||
|
|
1127
|
-
(submittedPlacement !== undefined &&
|
|
1128
|
-
submittedPlacement !== 'current_turn' &&
|
|
1129
|
-
submittedPlacement !== 'next_turn') ||
|
|
1130
|
-
(submittedContentDigest !== undefined && !isSha256Digest(submittedContentDigest))) {
|
|
1131
|
-
throw new Error(`Invalid root turn source message at index ${index}`);
|
|
1132
|
-
}
|
|
1133
|
-
if (messageIds.has(messageId)) {
|
|
1134
|
-
throw new Error(`Duplicate root turn source message id: ${messageId}`);
|
|
1135
|
-
}
|
|
1136
|
-
messageIds.add(messageId);
|
|
1137
|
-
return Object.freeze({
|
|
1138
|
-
messageId,
|
|
1139
|
-
content: normalizeRootTurnMessageContent(content, `root turn source message content at index ${index}`, MAX_ATTACHMENT_COUNT),
|
|
1140
|
-
...(submittedContentDigest !== undefined ? { submittedContentDigest } : {}),
|
|
1141
|
-
...(submittedPlacement !== undefined ? { submittedPlacement } : {}),
|
|
1142
|
-
...(submittedIntent !== undefined
|
|
1143
|
-
? { submittedIntent: normalizeSubmittedTurnIntent(submittedIntent) }
|
|
1144
|
-
: {}),
|
|
1145
|
-
...(skillInvocation !== undefined
|
|
1146
|
-
? { skillInvocation: decodeSkillInvocationResult(skillInvocation) }
|
|
1147
|
-
: {}),
|
|
1148
|
-
placement,
|
|
1149
|
-
disposition,
|
|
1150
|
-
});
|
|
1151
|
-
});
|
|
1152
|
-
return Object.freeze(normalized);
|
|
1153
|
-
}
|
|
1154
|
-
function rootTurnAdmissionPayloadsEqual(left, right) {
|
|
1155
|
-
return (isDeepStrictEqual(left.execution, right.execution) &&
|
|
1156
|
-
isDeepStrictEqual(left.turnOrchestration, right.turnOrchestration) &&
|
|
1157
|
-
isDeepStrictEqual(left.skillInvocation, right.skillInvocation) &&
|
|
1158
|
-
isDeepStrictEqual(left.authorization, right.authorization) &&
|
|
1159
|
-
(left.normalizedInput === null || right.normalizedInput === null
|
|
1160
|
-
? left.normalizedInput === right.normalizedInput
|
|
1161
|
-
: messageContentsEqual(left.normalizedInput, right.normalizedInput)) &&
|
|
1162
|
-
left.sourceMessages.length === right.sourceMessages.length &&
|
|
1163
|
-
left.sourceMessages.every((source, index) => {
|
|
1164
|
-
const other = right.sourceMessages[index];
|
|
1165
|
-
return (other !== undefined &&
|
|
1166
|
-
source.messageId === other.messageId &&
|
|
1167
|
-
source.placement === other.placement &&
|
|
1168
|
-
source.disposition === other.disposition &&
|
|
1169
|
-
source.submittedContentDigest === other.submittedContentDigest &&
|
|
1170
|
-
(source.submittedPlacement ?? source.placement) ===
|
|
1171
|
-
(other.submittedPlacement ?? other.placement) &&
|
|
1172
|
-
submittedTurnIntentsEqual(source.submittedIntent, other.submittedIntent) &&
|
|
1173
|
-
isDeepStrictEqual(source.skillInvocation, other.skillInvocation) &&
|
|
1174
|
-
messageContentsEqual(source.content, other.content));
|
|
1175
|
-
}));
|
|
1176
|
-
}
|
|
1177
|
-
function assertRootTurnAdmissionRecordSize(admission) {
|
|
1178
|
-
assertRootTurnAdmissionSerializedSize(`${JSON.stringify(admission)}\n`);
|
|
1179
|
-
}
|
|
1180
|
-
function assertRootTurnAdmissionSerializedSize(serialized) {
|
|
1181
|
-
if (Buffer.byteLength(serialized, 'utf8') > ROOT_TURN_ADMISSION_MAX_RECORD_BYTES) {
|
|
1182
|
-
throw new Error('Invalid root turn admission: record exceeds size limit');
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
function assertRootTurnAdmissionContract(admission) {
|
|
1186
|
-
const execution = admission.execution;
|
|
1187
|
-
const providerRetry = execution.kind === 'linked_child_provider_retry';
|
|
1188
|
-
const inputlessExecution = execution.kind === 'safe_boundary_continuation' || execution.kind === 'context_compact';
|
|
1189
|
-
const allowsQueueSources = execution.kind === 'external_message' ||
|
|
1190
|
-
(execution.kind === 'workhub_coordination' && execution.operation !== 'action');
|
|
1191
|
-
const sourceBatch = allowsQueueSources && admission.sourceMessages.length > 1;
|
|
1192
|
-
const messageLessExecution = inputlessExecution || providerRetry || sourceBatch;
|
|
1193
|
-
if (execution.kind === 'agent_graph_supervisor_wake') {
|
|
1194
|
-
if (admission.turnOrchestration?.mode !== 'graph' ||
|
|
1195
|
-
admission.turnOrchestration.source !== 'host_api') {
|
|
1196
|
-
throw new Error('Invalid root turn admission contract: Agent Graph supervisor wake requires Host Graph orchestration');
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
else if (admission.turnOrchestration && execution.kind !== 'external_message') {
|
|
1200
|
-
throw new Error('Invalid root turn admission contract: orchestration override is not authorized for this execution');
|
|
1201
|
-
}
|
|
1202
|
-
if ((admission.userMessageId === null) !== messageLessExecution) {
|
|
1203
|
-
throw new Error('Invalid root turn admission contract: execution has an invalid UserMessage requirement');
|
|
1204
|
-
}
|
|
1205
|
-
if ((admission.normalizedInput === null) !== inputlessExecution) {
|
|
1206
|
-
throw new Error('Invalid root turn admission contract: execution has an invalid input requirement');
|
|
1207
|
-
}
|
|
1208
|
-
if (!allowsQueueSources && admission.sourceMessages.length !== 0) {
|
|
1209
|
-
throw new Error('Invalid root turn admission contract: host-authored execution cannot have source messages');
|
|
1210
|
-
}
|
|
1211
|
-
if (admission.skillInvocation && execution.kind !== 'external_message') {
|
|
1212
|
-
throw new Error('Invalid root turn admission contract: Skill invocation requires external message execution');
|
|
1213
|
-
}
|
|
1214
|
-
if (admission.authorization &&
|
|
1215
|
-
execution.kind !== 'external_message' &&
|
|
1216
|
-
execution.kind !== 'regenerate') {
|
|
1217
|
-
throw new Error('Invalid root turn admission contract: authorization proof requires external message or regenerate execution');
|
|
1218
|
-
}
|
|
1219
|
-
if (execution.kind === 'claimed_agent_graph_intent') {
|
|
1220
|
-
if (execution.claim.targetSessionId !== admission.sessionId ||
|
|
1221
|
-
execution.claim.targetTurnId !== admission.turnId ||
|
|
1222
|
-
execution.claim.targetRunId !== admission.runId) {
|
|
1223
|
-
throw new Error('Invalid root turn admission contract: agent graph claim target does not match admission identity');
|
|
1224
|
-
}
|
|
1225
|
-
if (admission.userMessageId === null) {
|
|
1226
|
-
throw new Error('Invalid root turn admission contract: agent graph execution requires a UserMessage');
|
|
1227
|
-
}
|
|
1228
|
-
}
|
|
1229
|
-
if ((execution.kind === 'linked_child_resume' ||
|
|
1230
|
-
execution.kind === 'linked_child_provider_retry') &&
|
|
1231
|
-
execution.sourceRunId === admission.runId) {
|
|
1232
|
-
throw new Error('Invalid root turn admission contract: linked child source Run cannot be the admitted Run');
|
|
1233
|
-
}
|
|
1234
|
-
if (execution.kind === 'safe_boundary_continuation' &&
|
|
1235
|
-
(execution.sourceRunId === admission.runId ||
|
|
1236
|
-
execution.sourceTurnId === admission.turnId ||
|
|
1237
|
-
execution.sourceInvocationId === execution.targetInvocationId ||
|
|
1238
|
-
admission.normalizedInput !== null)) {
|
|
1239
|
-
throw new Error('Invalid root turn admission contract: safe-boundary continuation identity is invalid');
|
|
1240
|
-
}
|
|
1241
|
-
if (execution.kind === 'regenerate' && execution.sourceTurnId === admission.turnId) {
|
|
1242
|
-
throw new Error('Invalid root turn admission contract: regenerate source Turn cannot be the admitted Turn');
|
|
1243
|
-
}
|
|
1244
|
-
if (execution.kind === 'external_message' &&
|
|
1245
|
-
admission.sourceMessages.some((source) => source.disposition === 'turn_started' && source.messageId !== admission.userMessageId)) {
|
|
1246
|
-
throw new Error('Invalid root turn admission contract: turn-started source must own the UserMessage');
|
|
1247
|
-
}
|
|
1248
|
-
}
|
|
1249
|
-
function deepFreezeRootTurnAdmission(admission) {
|
|
1250
|
-
if (admission.execution.kind === 'claimed_agent_graph_intent') {
|
|
1251
|
-
Object.freeze(admission.execution.claim);
|
|
1252
|
-
}
|
|
1253
|
-
Object.freeze(admission.execution);
|
|
1254
|
-
if (admission.turnOrchestration)
|
|
1255
|
-
Object.freeze(admission.turnOrchestration);
|
|
1256
|
-
if (admission.skillInvocation)
|
|
1257
|
-
Object.freeze(admission.skillInvocation);
|
|
1258
|
-
if (admission.authorization)
|
|
1259
|
-
Object.freeze(admission.authorization);
|
|
1260
|
-
if (admission.normalizedInput)
|
|
1261
|
-
deepFreezeRootTurnMessageContent(admission.normalizedInput);
|
|
1262
|
-
for (const sourceMessage of admission.sourceMessages) {
|
|
1263
|
-
deepFreezeRootTurnMessageContent(sourceMessage.content);
|
|
1264
|
-
Object.freeze(sourceMessage);
|
|
1265
|
-
}
|
|
1266
|
-
Object.freeze(admission.sourceMessages);
|
|
1267
|
-
return Object.freeze(admission);
|
|
1268
|
-
}
|
|
1269
|
-
function normalizeTurnOrchestration(value) {
|
|
1270
|
-
if (value === undefined)
|
|
1271
|
-
return undefined;
|
|
1272
|
-
if (!isPlainRecord(value) ||
|
|
1273
|
-
!hasExactKeys(value, ['mode', 'source']) ||
|
|
1274
|
-
!isOrchestrationMode(value.mode) ||
|
|
1275
|
-
!isTurnOrchestrationSource(value.source)) {
|
|
1276
|
-
throw new Error('Invalid root turn orchestration');
|
|
1277
|
-
}
|
|
1278
|
-
return Object.freeze({ mode: value.mode, source: value.source });
|
|
1279
|
-
}
|
|
1280
|
-
function normalizeRootTurnAdmissionAuthorization(value) {
|
|
1281
|
-
if (value === undefined)
|
|
1282
|
-
return undefined;
|
|
1283
|
-
if (!isPlainRecord(value) ||
|
|
1284
|
-
!hasExactKeys(value, [
|
|
1285
|
-
'kind',
|
|
1286
|
-
'requestId',
|
|
1287
|
-
'principalId',
|
|
1288
|
-
'grantId',
|
|
1289
|
-
'approvedAt',
|
|
1290
|
-
'approvedBy',
|
|
1291
|
-
]) ||
|
|
1292
|
-
value.kind !== 'session_turn_access_request' ||
|
|
1293
|
-
typeof value.requestId !== 'string' ||
|
|
1294
|
-
!isSafeId(value.requestId) ||
|
|
1295
|
-
typeof value.principalId !== 'string' ||
|
|
1296
|
-
!isGraphControlIdentity(value.principalId) ||
|
|
1297
|
-
typeof value.grantId !== 'string' ||
|
|
1298
|
-
!isSafeId(value.grantId) ||
|
|
1299
|
-
!Number.isSafeInteger(value.approvedAt) ||
|
|
1300
|
-
value.approvedAt < 0 ||
|
|
1301
|
-
typeof value.approvedBy !== 'string' ||
|
|
1302
|
-
!isGraphControlIdentity(value.approvedBy)) {
|
|
1303
|
-
throw new Error('Invalid root turn admission authorization');
|
|
1304
|
-
}
|
|
1305
|
-
return Object.freeze({
|
|
1306
|
-
kind: value.kind,
|
|
1307
|
-
requestId: value.requestId,
|
|
1308
|
-
principalId: value.principalId,
|
|
1309
|
-
grantId: value.grantId,
|
|
1310
|
-
approvedAt: value.approvedAt,
|
|
1311
|
-
approvedBy: value.approvedBy,
|
|
1312
|
-
});
|
|
1313
|
-
}
|
|
1314
|
-
function hasRootTurnAdmissionKeys(record) {
|
|
1315
|
-
const keys = [
|
|
1316
|
-
'schemaVersion',
|
|
1317
|
-
'sessionId',
|
|
1318
|
-
'turnId',
|
|
1319
|
-
'runId',
|
|
1320
|
-
'userMessageId',
|
|
1321
|
-
'execution',
|
|
1322
|
-
'previousRootTurnId',
|
|
1323
|
-
'normalizedInput',
|
|
1324
|
-
'sourceMessages',
|
|
1325
|
-
'admittedAt',
|
|
1326
|
-
];
|
|
1327
|
-
const optionalKeys = ['turnOrchestration', 'skillInvocation', 'authorization'].filter((key) => Object.hasOwn(record, key));
|
|
1328
|
-
return hasExactKeys(record, [...keys, ...optionalKeys]);
|
|
1329
|
-
}
|
|
1330
|
-
function normalizeRootExecutionDescriptor(value) {
|
|
1331
|
-
if (!isPlainRecord(value) || typeof value.kind !== 'string') {
|
|
1332
|
-
throw new Error('Invalid root execution descriptor');
|
|
1333
|
-
}
|
|
1334
|
-
if (value.kind === 'external_message') {
|
|
1335
|
-
const allowedKeys = ['kind', 'inputDigest', 'maxSteps'];
|
|
1336
|
-
if (!Object.keys(value).every((key) => allowedKeys.includes(key))) {
|
|
1337
|
-
throw new Error('Invalid root execution descriptor');
|
|
1338
|
-
}
|
|
1339
|
-
if (value.inputDigest !== undefined && !isSha256Digest(value.inputDigest)) {
|
|
1340
|
-
throw new Error('Invalid root execution descriptor');
|
|
1341
|
-
}
|
|
1342
|
-
if (value.maxSteps !== undefined &&
|
|
1343
|
-
(typeof value.maxSteps !== 'number' ||
|
|
1344
|
-
!Number.isSafeInteger(value.maxSteps) ||
|
|
1345
|
-
value.maxSteps <= 0)) {
|
|
1346
|
-
throw new Error('Invalid root execution descriptor');
|
|
1347
|
-
}
|
|
1348
|
-
return Object.freeze({
|
|
1349
|
-
kind: 'external_message',
|
|
1350
|
-
...(value.inputDigest !== undefined ? { inputDigest: value.inputDigest } : {}),
|
|
1351
|
-
...(value.maxSteps !== undefined ? { maxSteps: value.maxSteps } : {}),
|
|
1352
|
-
});
|
|
1353
|
-
}
|
|
1354
|
-
if (value.kind === 'workhub_coordination') {
|
|
1355
|
-
const routingDecision = normalizeWorkHubRoutingDecision(value.routingDecision);
|
|
1356
|
-
if (!hasExactKeys(value, [
|
|
1357
|
-
'kind',
|
|
1358
|
-
'inputDigest',
|
|
1359
|
-
...(value.capabilityBinding === undefined ? [] : ['capabilityBinding']),
|
|
1360
|
-
...(value.routingDecision === undefined ? [] : ['routingDecision']),
|
|
1361
|
-
...(value.operation === undefined ? [] : ['operation']),
|
|
1362
|
-
...(value.actionId === undefined ? [] : ['actionId']),
|
|
1363
|
-
]) ||
|
|
1364
|
-
(value.capabilityBinding !== undefined && !isSha256Digest(value.capabilityBinding)) ||
|
|
1365
|
-
(value.actionId !== undefined && value.operation !== 'action') ||
|
|
1366
|
-
(value.operation !== undefined && routingDecision !== undefined) ||
|
|
1367
|
-
(value.operation !== undefined && value.operation !== 'action') ||
|
|
1368
|
-
(value.actionId !== undefined &&
|
|
1369
|
-
(typeof value.actionId !== 'string' || !isSafeId(value.actionId))) ||
|
|
1370
|
-
!isSha256Digest(value.inputDigest)) {
|
|
1371
|
-
throw new Error('Invalid root execution descriptor');
|
|
1372
|
-
}
|
|
1373
|
-
return Object.freeze({
|
|
1374
|
-
kind: 'workhub_coordination',
|
|
1375
|
-
...(value.operation === 'action' ? { operation: 'action' } : {}),
|
|
1376
|
-
inputDigest: value.inputDigest,
|
|
1377
|
-
...(isSha256Digest(value.capabilityBinding)
|
|
1378
|
-
? { capabilityBinding: value.capabilityBinding }
|
|
1379
|
-
: {}),
|
|
1380
|
-
...(typeof value.actionId === 'string' ? { actionId: value.actionId } : {}),
|
|
1381
|
-
...(routingDecision ? { routingDecision } : {}),
|
|
1382
|
-
});
|
|
1383
|
-
}
|
|
1384
|
-
if (value.kind === 'regenerate') {
|
|
1385
|
-
if (!hasExactKeys(value, ['kind', 'sourceTurnId']) ||
|
|
1386
|
-
typeof value.sourceTurnId !== 'string' ||
|
|
1387
|
-
!isSafeId(value.sourceTurnId)) {
|
|
1388
|
-
throw new Error('Invalid root execution descriptor');
|
|
1389
|
-
}
|
|
1390
|
-
return Object.freeze({ kind: 'regenerate', sourceTurnId: value.sourceTurnId });
|
|
1391
|
-
}
|
|
1392
|
-
if (value.kind === 'context_compact') {
|
|
1393
|
-
if (!hasExactKeys(value, ['kind']))
|
|
1394
|
-
throw new Error('Invalid root execution descriptor');
|
|
1395
|
-
return Object.freeze({ kind: 'context_compact' });
|
|
1396
|
-
}
|
|
1397
|
-
if (value.kind === 'scheduled_task') {
|
|
1398
|
-
if (!hasExactKeys(value, [
|
|
1399
|
-
'kind',
|
|
1400
|
-
'scheduledTaskId',
|
|
1401
|
-
...(Object.hasOwn(value, 'executionFingerprint') ? ['executionFingerprint'] : []),
|
|
1402
|
-
]) ||
|
|
1403
|
-
typeof value.scheduledTaskId !== 'string' ||
|
|
1404
|
-
!isSafeId(value.scheduledTaskId) ||
|
|
1405
|
-
(value.executionFingerprint !== undefined && !isSha256Digest(value.executionFingerprint))) {
|
|
1406
|
-
throw new Error('Invalid root execution descriptor');
|
|
1407
|
-
}
|
|
1408
|
-
return Object.freeze({
|
|
1409
|
-
kind: 'scheduled_task',
|
|
1410
|
-
scheduledTaskId: value.scheduledTaskId,
|
|
1411
|
-
...(value.executionFingerprint !== undefined
|
|
1412
|
-
? { executionFingerprint: value.executionFingerprint }
|
|
1413
|
-
: {}),
|
|
1414
|
-
});
|
|
1415
|
-
}
|
|
1416
|
-
if (value.kind === 'automation' || value.kind === 'legacy_automation') {
|
|
1417
|
-
if (!hasExactKeys(value, ['kind', 'automationId']) ||
|
|
1418
|
-
typeof value.automationId !== 'string' ||
|
|
1419
|
-
!isSafeId(value.automationId)) {
|
|
1420
|
-
throw new Error('Invalid root execution descriptor');
|
|
1421
|
-
}
|
|
1422
|
-
return Object.freeze({ kind: 'legacy_automation', automationId: value.automationId });
|
|
1423
|
-
}
|
|
1424
|
-
if (value.kind === 'goal') {
|
|
1425
|
-
if (!hasExactKeys(value, ['kind', 'goalId']) ||
|
|
1426
|
-
typeof value.goalId !== 'string' ||
|
|
1427
|
-
!isSafeId(value.goalId)) {
|
|
1428
|
-
throw new Error('Invalid root execution descriptor');
|
|
1429
|
-
}
|
|
1430
|
-
return Object.freeze({ kind: 'goal', goalId: value.goalId });
|
|
1431
|
-
}
|
|
1432
|
-
if (value.kind === 'agent_graph_supervisor_wake') {
|
|
1433
|
-
if (!hasExactKeys(value, ['kind', 'graphId', 'wakeId', 'attemptId']) ||
|
|
1434
|
-
typeof value.graphId !== 'string' ||
|
|
1435
|
-
!isGraphControlIdentity(value.graphId) ||
|
|
1436
|
-
typeof value.wakeId !== 'string' ||
|
|
1437
|
-
!isGraphControlIdentity(value.wakeId) ||
|
|
1438
|
-
!value.wakeId.startsWith(`${value.graphId}:`) ||
|
|
1439
|
-
typeof value.attemptId !== 'string' ||
|
|
1440
|
-
!isGraphControlIdentity(value.attemptId)) {
|
|
1441
|
-
throw new Error('Invalid root execution descriptor');
|
|
1442
|
-
}
|
|
1443
|
-
return Object.freeze({
|
|
1444
|
-
kind: value.kind,
|
|
1445
|
-
graphId: value.graphId,
|
|
1446
|
-
wakeId: value.wakeId,
|
|
1447
|
-
attemptId: value.attemptId,
|
|
1448
|
-
});
|
|
1449
|
-
}
|
|
1450
|
-
if (value.kind === 'safe_boundary_continuation') {
|
|
1451
|
-
const keys = [
|
|
1452
|
-
'kind',
|
|
1453
|
-
'sourceInvocationId',
|
|
1454
|
-
'sourceRunId',
|
|
1455
|
-
'sourceTurnId',
|
|
1456
|
-
'sourceRuntimeEventHighWater',
|
|
1457
|
-
'claimId',
|
|
1458
|
-
'boundaryDigest',
|
|
1459
|
-
'providerReplayDigest',
|
|
1460
|
-
'safetyDigest',
|
|
1461
|
-
'targetInvocationId',
|
|
1462
|
-
];
|
|
1463
|
-
if (!hasExactKeys(value, keys) ||
|
|
1464
|
-
typeof value.sourceInvocationId !== 'string' ||
|
|
1465
|
-
!isSafeId(value.sourceInvocationId) ||
|
|
1466
|
-
typeof value.sourceRunId !== 'string' ||
|
|
1467
|
-
!isSafeId(value.sourceRunId) ||
|
|
1468
|
-
typeof value.sourceTurnId !== 'string' ||
|
|
1469
|
-
!isSafeId(value.sourceTurnId) ||
|
|
1470
|
-
!Number.isSafeInteger(value.sourceRuntimeEventHighWater) ||
|
|
1471
|
-
value.sourceRuntimeEventHighWater < 1 ||
|
|
1472
|
-
typeof value.claimId !== 'string' ||
|
|
1473
|
-
!isSafeId(value.claimId) ||
|
|
1474
|
-
!isSha256Digest(value.boundaryDigest) ||
|
|
1475
|
-
!isSha256Digest(value.providerReplayDigest) ||
|
|
1476
|
-
!isSha256Digest(value.safetyDigest) ||
|
|
1477
|
-
typeof value.targetInvocationId !== 'string' ||
|
|
1478
|
-
!isSafeId(value.targetInvocationId)) {
|
|
1479
|
-
throw new Error('Invalid root execution descriptor');
|
|
1480
|
-
}
|
|
1481
|
-
return Object.freeze({
|
|
1482
|
-
kind: value.kind,
|
|
1483
|
-
sourceInvocationId: value.sourceInvocationId,
|
|
1484
|
-
sourceRunId: value.sourceRunId,
|
|
1485
|
-
sourceTurnId: value.sourceTurnId,
|
|
1486
|
-
sourceRuntimeEventHighWater: value.sourceRuntimeEventHighWater,
|
|
1487
|
-
claimId: value.claimId,
|
|
1488
|
-
boundaryDigest: value.boundaryDigest,
|
|
1489
|
-
providerReplayDigest: value.providerReplayDigest,
|
|
1490
|
-
safetyDigest: value.safetyDigest,
|
|
1491
|
-
targetInvocationId: value.targetInvocationId,
|
|
1492
|
-
});
|
|
1493
|
-
}
|
|
1494
|
-
if (value.kind === 'claimed_agent_graph_intent') {
|
|
1495
|
-
if (!hasExactKeys(value, ['kind', 'claim', 'agentId', 'agentName']) ||
|
|
1496
|
-
typeof value.agentId !== 'string' ||
|
|
1497
|
-
!isSafeId(value.agentId) ||
|
|
1498
|
-
typeof value.agentName !== 'string' ||
|
|
1499
|
-
value.agentName.length === 0 ||
|
|
1500
|
-
Buffer.byteLength(value.agentName, 'utf8') > 256) {
|
|
1501
|
-
throw new Error('Invalid root execution descriptor');
|
|
1502
|
-
}
|
|
1503
|
-
let claim;
|
|
1504
|
-
try {
|
|
1505
|
-
claim = decodeAgentGraphIntentClaim(value.claim);
|
|
1506
|
-
}
|
|
1507
|
-
catch {
|
|
1508
|
-
throw new Error('Invalid root execution descriptor');
|
|
1509
|
-
}
|
|
1510
|
-
Object.freeze(claim);
|
|
1511
|
-
return Object.freeze({
|
|
1512
|
-
kind: value.kind,
|
|
1513
|
-
claim,
|
|
1514
|
-
agentId: value.agentId,
|
|
1515
|
-
agentName: value.agentName,
|
|
1516
|
-
});
|
|
1517
|
-
}
|
|
1518
|
-
if (value.kind !== 'linked_child_initial' &&
|
|
1519
|
-
value.kind !== 'linked_child_resume' &&
|
|
1520
|
-
value.kind !== 'linked_child_provider_retry') {
|
|
1521
|
-
throw new Error('Invalid root execution descriptor');
|
|
1522
|
-
}
|
|
1523
|
-
const hasSource = value.kind !== 'linked_child_initial';
|
|
1524
|
-
if (!hasExactKeys(value, hasSource
|
|
1525
|
-
? ['kind', 'agentId', 'agentName', 'sourceRunId']
|
|
1526
|
-
: ['kind', 'agentId', 'agentName']) ||
|
|
1527
|
-
typeof value.agentId !== 'string' ||
|
|
1528
|
-
!isSafeId(value.agentId) ||
|
|
1529
|
-
typeof value.agentName !== 'string' ||
|
|
1530
|
-
value.agentName.length === 0 ||
|
|
1531
|
-
Buffer.byteLength(value.agentName, 'utf8') > 256 ||
|
|
1532
|
-
(hasSource && (typeof value.sourceRunId !== 'string' || !isSafeId(value.sourceRunId)))) {
|
|
1533
|
-
throw new Error('Invalid root execution descriptor');
|
|
1534
|
-
}
|
|
1535
|
-
if (value.kind === 'linked_child_initial') {
|
|
1536
|
-
return Object.freeze({
|
|
1537
|
-
kind: value.kind,
|
|
1538
|
-
agentId: value.agentId,
|
|
1539
|
-
agentName: value.agentName,
|
|
1540
|
-
});
|
|
1541
|
-
}
|
|
1542
|
-
return Object.freeze({
|
|
1543
|
-
kind: value.kind,
|
|
1544
|
-
agentId: value.agentId,
|
|
1545
|
-
agentName: value.agentName,
|
|
1546
|
-
sourceRunId: value.sourceRunId,
|
|
1547
|
-
});
|
|
1548
|
-
}
|
|
1549
|
-
function normalizeWorkHubRoutingDecision(value) {
|
|
1550
|
-
if (value === undefined)
|
|
1551
|
-
return undefined;
|
|
1552
|
-
if (!isPlainRecord(value) || typeof value.kind !== 'string') {
|
|
1553
|
-
throw new Error('Invalid WorkHub routing decision');
|
|
1554
|
-
}
|
|
1555
|
-
if (value.kind === 'routing' &&
|
|
1556
|
-
(value.disposition === 'answer_here' ||
|
|
1557
|
-
value.disposition === 'create_new' ||
|
|
1558
|
-
value.disposition === 'clarify') &&
|
|
1559
|
-
hasExactKeys(value, ['kind', 'disposition'])) {
|
|
1560
|
-
return Object.freeze({ kind: 'routing', disposition: value.disposition });
|
|
1561
|
-
}
|
|
1562
|
-
if (value.kind === 'routing' &&
|
|
1563
|
-
value.disposition === 'delegate_existing' &&
|
|
1564
|
-
typeof value.candidateSetId === 'string' &&
|
|
1565
|
-
/^sha256:[a-f0-9]{64}$/.test(value.candidateSetId) &&
|
|
1566
|
-
typeof value.candidateRef === 'string' &&
|
|
1567
|
-
isSafeId(value.candidateRef) &&
|
|
1568
|
-
hasExactKeys(value, ['kind', 'disposition', 'candidateSetId', 'candidateRef'])) {
|
|
1569
|
-
return Object.freeze({
|
|
1570
|
-
kind: 'routing',
|
|
1571
|
-
disposition: 'delegate_existing',
|
|
1572
|
-
candidateSetId: value.candidateSetId,
|
|
1573
|
-
candidateRef: value.candidateRef,
|
|
1574
|
-
});
|
|
1575
|
-
}
|
|
1576
|
-
if (value.kind === 'linked' &&
|
|
1577
|
-
(value.operation === 'correct' || value.operation === 'stop' || value.operation === 'resume') &&
|
|
1578
|
-
hasExactKeys(value, ['kind', 'operation'])) {
|
|
1579
|
-
return Object.freeze({ kind: 'linked', operation: value.operation });
|
|
1580
|
-
}
|
|
1581
|
-
throw new Error('Invalid WorkHub routing decision');
|
|
1582
|
-
}
|
|
1583
|
-
function deepFreezeRootTurnMessageContent(content) {
|
|
1584
|
-
for (const attachment of content.attachments ?? []) {
|
|
1585
|
-
Object.freeze(attachment.ref);
|
|
1586
|
-
Object.freeze(attachment);
|
|
1587
|
-
}
|
|
1588
|
-
if (content.attachments)
|
|
1589
|
-
Object.freeze(content.attachments);
|
|
1590
|
-
for (const reference of content.directoryReferences ?? [])
|
|
1591
|
-
Object.freeze(reference);
|
|
1592
|
-
if (content.directoryReferences)
|
|
1593
|
-
Object.freeze(content.directoryReferences);
|
|
1594
|
-
for (const quote of content.quotes ?? [])
|
|
1595
|
-
Object.freeze(quote);
|
|
1596
|
-
if (content.quotes)
|
|
1597
|
-
Object.freeze(content.quotes);
|
|
1598
|
-
Object.freeze(content);
|
|
1599
|
-
}
|
|
1600
|
-
function isPlainRecord(value) {
|
|
1601
|
-
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
1602
|
-
return false;
|
|
1603
|
-
const prototype = Object.getPrototypeOf(value);
|
|
1604
|
-
return prototype === Object.prototype || prototype === null;
|
|
1605
|
-
}
|
|
1606
|
-
function isSha256Digest(value) {
|
|
1607
|
-
return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value);
|
|
1608
|
-
}
|
|
1609
|
-
function hasExactKeys(record, expected) {
|
|
1610
|
-
const keys = Object.keys(record);
|
|
1611
|
-
return keys.length === expected.length && expected.every((key) => Object.hasOwn(record, key));
|
|
1612
|
-
}
|
|
1613
|
-
function sanitizeJson(_key, value) {
|
|
1614
|
-
return value === undefined ? undefined : value;
|
|
1615
|
-
}
|