maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907
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/acp/maka-acp-agent.js +2 -1
- package/dist/acp/session-configuration.js +143 -0
- package/dist/acp/session-registry.js +90 -4
- package/dist/cli-core.js +2 -0
- package/dist/pi-transcript.js +5 -12
- package/dist/pi-tui-runner.js +74 -4
- package/dist/runtime-host-cli-context.js +167 -78
- package/dist/runtime-host-cli-installation.js +8 -2
- package/dist/runtime-host-cli.js +31 -1
- package/dist/runtime-host-handoff-surface.js +81 -0
- package/dist/runtime-host-installed-update-bootstrap.js +13 -0
- package/dist/runtime-host-installed-update-coordinator.js +33 -0
- package/dist/runtime-host-lifecycle-transaction.js +9 -1
- package/dist/runtime-host-local-handoff.js +37 -4
- package/dist/runtime-host-local-managed-activation.js +84 -0
- package/dist/runtime-host-local-source-retirement.js +18 -2
- package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
- package/dist/runtime-host-operator-retirement.js +50 -0
- package/dist/runtime-host-service-manager.js +3 -0
- package/dist/runtime-host-session-driver.js +4 -25
- package/dist/runtime-host-session-update.js +62 -0
- package/dist/runtime-host-tui-command.js +38 -73
- package/dist/runtime-host-tui-context.js +1 -0
- package/dist/runtime-host-tui-owner.js +226 -0
- package/dist/tui-copy-catalog.js +140 -3
- package/dist/tui-host-owner-copy.js +24 -0
- package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
- package/node_modules/@maka/core/dist/bot-events.js +18 -63
- package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
- package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
- package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
- package/node_modules/@maka/core/dist/model-failure.js +40 -0
- package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
- package/node_modules/@maka/core/dist/model-metadata.js +3 -3
- package/node_modules/@maka/core/dist/model-web-search.js +5 -4
- package/node_modules/@maka/core/dist/provider-registry.js +45 -4
- package/node_modules/@maka/core/dist/record-schema.js +22 -2
- package/node_modules/@maka/core/dist/redaction.js +41 -58
- package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
- package/node_modules/@maka/core/dist/runtime-event.js +37 -6
- package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
- package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
- package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
- package/node_modules/@maka/core/dist/session-trace.js +5 -1
- package/node_modules/@maka/core/dist/session.js +54 -52
- package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
- package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
- package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
- package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
- package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
- package/node_modules/@maka/core/package.json +4 -0
- package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
- package/node_modules/@maka/mcp/dist/index.js +131 -1
- package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
- package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
- package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
- package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
- package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
- package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
- package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
- package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
- package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
- package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
- package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
- package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
- package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
- package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
- package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
- package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
- package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
- package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
- package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
- package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
- package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
- package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
- package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
- package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
- package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
- package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
- package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
- package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
- package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
- package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
- package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
- package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
- package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
- package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
- package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
- package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
- package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
- package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
- package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
- package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
- package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
- package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
- package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
- package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
- package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
- package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
- package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
- package/node_modules/@maka/runtime/package.json +1 -0
- package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
- package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
- package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
- package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
- package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
- package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
- package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
- package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
- package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
- package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
- package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
- package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
- package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
- package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
- package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
- package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
- package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
- package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
- package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
- package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
- package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
- package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
- package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
- package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
- package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
- package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
- package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
- package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
- package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
- package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
- package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
- package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
- package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
- package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
- package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
- package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
- package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
- package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
- package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
- package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
- package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
- package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
- package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
- package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
- package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
- package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
- package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
- package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
- package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
- package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
- package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
- package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
- package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
- package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
- package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
- package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
- package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
- package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
- package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
- package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
- package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
- package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
- package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
- package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
- package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
- package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
- package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
- package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
- package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
- package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
- package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
- package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
- package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
- package/node_modules/@maka/storage/dist/session-repository.js +767 -0
- package/node_modules/@maka/storage/dist/session-store.js +25 -99
- package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
- package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
- package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
- package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
- package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
- package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
- package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
- package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
- package/node_modules/@maka/storage/package.json +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1012 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Licensed to the Apache Software Foundation (ASF) under one
|
|
3
|
+
* or more contributor license agreements. See the NOTICE file
|
|
4
|
+
* distributed with this work for additional information
|
|
5
|
+
* regarding copyright ownership. The ASF licenses this file
|
|
6
|
+
* to you under the Apache License, Version 2.0 (the
|
|
7
|
+
* "License"); you may not use this file except in compliance
|
|
8
|
+
* with the License. You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing,
|
|
13
|
+
* software distributed under the License is distributed on an
|
|
14
|
+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
15
|
+
* KIND, either express or implied. See the License for the
|
|
16
|
+
* specific language governing permissions and limitations
|
|
17
|
+
* under the License.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
20
|
+
import { constants as fsConstants } from 'node:fs';
|
|
21
|
+
import { createReadStream } from 'node:fs';
|
|
22
|
+
import { mkdir, open, readFile, rename, rm } from 'node:fs/promises';
|
|
23
|
+
import { dirname, join } from 'node:path';
|
|
24
|
+
import { isNonEmptyUnicodeString, isSha256Digest, } from './session-bundle-contract.js';
|
|
25
|
+
import { syncDirectory, syncDirectoryChain } from './stable-storage.js';
|
|
26
|
+
import { createSessionCheckpointManifestV1, encodeSessionCheckpointManifestV1, SESSION_CHECKPOINT_MANIFEST_MEDIA_TYPE, SessionRepositoryError, } from './session-repository.js';
|
|
27
|
+
import { withProcessLifetimeFileUpdateLock } from './process-lifetime-file-update-lock.js';
|
|
28
|
+
const MAX_IDENTIFIER_LENGTH = 512;
|
|
29
|
+
const MAX_OBJECT_REF_LENGTH = 2_048;
|
|
30
|
+
const STATE_FILE_NAME = 'session-repository-v1.json';
|
|
31
|
+
/**
|
|
32
|
+
* Opens the durable local adapter. Object bytes are immutable files while the
|
|
33
|
+
* small Session control plane is one atomically replaced state document.
|
|
34
|
+
*/
|
|
35
|
+
export async function openFileSessionRepository(input) {
|
|
36
|
+
if (!isRecord(input))
|
|
37
|
+
throw new TypeError('File Session Repository options must be an object');
|
|
38
|
+
const storageRoot = requireIdentifier(input.storageRoot, 'Storage root', MAX_OBJECT_REF_LENGTH);
|
|
39
|
+
await mkdir(storageRoot, { recursive: true, mode: 0o700 });
|
|
40
|
+
const objectStore = new FileImmutableObjectStore(join(storageRoot, 'objects'), storageRoot);
|
|
41
|
+
return new FileSessionRepositoryAdapter(join(storageRoot, STATE_FILE_NAME), objectStore);
|
|
42
|
+
}
|
|
43
|
+
class FileSessionRepositoryAdapter {
|
|
44
|
+
statePath;
|
|
45
|
+
objectStore;
|
|
46
|
+
forkIdempotencyRetention = 'indefinite';
|
|
47
|
+
constructor(statePath, objectStore) {
|
|
48
|
+
this.statePath = statePath;
|
|
49
|
+
this.objectStore = objectStore;
|
|
50
|
+
}
|
|
51
|
+
async checkoutCurrent(sessionId) {
|
|
52
|
+
const admittedSessionId = requireIdentifier(sessionId, 'Session identity');
|
|
53
|
+
const state = await this.readState();
|
|
54
|
+
const session = findSession(state, admittedSessionId);
|
|
55
|
+
if (!session)
|
|
56
|
+
throw repositoryError('session_not_found', 'Cloud Session was not found');
|
|
57
|
+
const result = copyCommittedSessionRevision(session.head);
|
|
58
|
+
await assertCheckpointReadable(this.objectStore, result.checkpoint);
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
async checkoutExact(ref) {
|
|
62
|
+
const requested = admitRevisionRef(ref, 'Session revision reference');
|
|
63
|
+
const state = await this.readState();
|
|
64
|
+
const session = findSession(state, requested.sessionId);
|
|
65
|
+
if (!session)
|
|
66
|
+
throw repositoryError('session_not_found', 'Cloud Session was not found');
|
|
67
|
+
if (session.head.ref.revision !== requested.revision) {
|
|
68
|
+
throw repositoryError('revision_not_available', 'Requested Session revision is not available');
|
|
69
|
+
}
|
|
70
|
+
const result = copyCommittedSessionRevision(session.head);
|
|
71
|
+
await assertCheckpointReadable(this.objectStore, result.checkpoint);
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
async createSession(input) {
|
|
75
|
+
const admitted = admitCreateSessionInput(input);
|
|
76
|
+
// Match the contract's linearization/error precedence: an existing Session
|
|
77
|
+
// is authoritative before an unrelated candidate object is consulted.
|
|
78
|
+
const beforeVerification = await this.readState();
|
|
79
|
+
const existing = findSession(beforeVerification, admitted.sessionId);
|
|
80
|
+
if (existing) {
|
|
81
|
+
const reconciled = reconcileExistingSessionCreate(existing, admitted);
|
|
82
|
+
await assertCheckpointReadable(this.objectStore, reconciled.checkpoint);
|
|
83
|
+
return copyCommittedSessionRevision(reconciled);
|
|
84
|
+
}
|
|
85
|
+
await assertCheckpointReadable(this.objectStore, admitted.checkpoint);
|
|
86
|
+
const result = await this.mutate((state) => {
|
|
87
|
+
const concurrent = findSession(state, admitted.sessionId);
|
|
88
|
+
if (concurrent)
|
|
89
|
+
return reconcileExistingSessionCreate(concurrent, admitted);
|
|
90
|
+
if (admitted.createdByForkId !== undefined)
|
|
91
|
+
assertPendingForkCreate(state, admitted);
|
|
92
|
+
const initial = committedRevision({
|
|
93
|
+
sessionId: admitted.sessionId,
|
|
94
|
+
revision: 'r1',
|
|
95
|
+
agentId: admitted.agentId,
|
|
96
|
+
checkpoint: admitted.checkpoint,
|
|
97
|
+
lastCommittedActivationId: admitted.lastCommittedActivationId,
|
|
98
|
+
forkedFrom: admitted.forkedFrom,
|
|
99
|
+
});
|
|
100
|
+
state.sessions.push({
|
|
101
|
+
sessionId: admitted.sessionId,
|
|
102
|
+
agentId: admitted.agentId,
|
|
103
|
+
head: initial,
|
|
104
|
+
nextRevisionNumber: 2,
|
|
105
|
+
...(admitted.forkedFrom === undefined ? {} : { forkedFrom: admitted.forkedFrom }),
|
|
106
|
+
...(admitted.createdByForkId === undefined
|
|
107
|
+
? {}
|
|
108
|
+
: { createdByForkId: admitted.createdByForkId }),
|
|
109
|
+
createdRevision: initial,
|
|
110
|
+
});
|
|
111
|
+
return initial;
|
|
112
|
+
});
|
|
113
|
+
await assertCheckpointReadable(this.objectStore, result.checkpoint);
|
|
114
|
+
return copyCommittedSessionRevision(result);
|
|
115
|
+
}
|
|
116
|
+
async commit(input) {
|
|
117
|
+
const admitted = admitCommitSessionRevisionInput(input);
|
|
118
|
+
const existing = await this.readState();
|
|
119
|
+
const prior = findCommit(existing, admitted.sessionId, admitted.commitId);
|
|
120
|
+
if (prior) {
|
|
121
|
+
assertSameCommitInput(prior.input, admitted);
|
|
122
|
+
await assertCheckpointReadable(this.objectStore, prior.result.checkpoint);
|
|
123
|
+
return copyCommittedSessionRevision(prior.result);
|
|
124
|
+
}
|
|
125
|
+
const session = findSession(existing, admitted.sessionId);
|
|
126
|
+
if (!session)
|
|
127
|
+
throw repositoryError('session_not_found', 'Cloud Session was not found');
|
|
128
|
+
if (session.head.ref.revision !== admitted.expectedRevision) {
|
|
129
|
+
throw repositoryError('revision_conflict', 'Cloud Session head changed before commit');
|
|
130
|
+
}
|
|
131
|
+
await assertCheckpointReadable(this.objectStore, admitted.checkpoint);
|
|
132
|
+
const result = await this.mutate((state) => {
|
|
133
|
+
const repeated = findCommit(state, admitted.sessionId, admitted.commitId);
|
|
134
|
+
if (repeated) {
|
|
135
|
+
assertSameCommitInput(repeated.input, admitted);
|
|
136
|
+
return repeated.result;
|
|
137
|
+
}
|
|
138
|
+
const session = findSession(state, admitted.sessionId);
|
|
139
|
+
if (!session)
|
|
140
|
+
throw repositoryError('session_not_found', 'Cloud Session was not found');
|
|
141
|
+
if (session.head.ref.revision !== admitted.expectedRevision) {
|
|
142
|
+
throw repositoryError('revision_conflict', 'Cloud Session head changed before commit');
|
|
143
|
+
}
|
|
144
|
+
const result = committedRevision({
|
|
145
|
+
sessionId: session.sessionId,
|
|
146
|
+
revision: `r${session.nextRevisionNumber}`,
|
|
147
|
+
agentId: session.agentId,
|
|
148
|
+
checkpoint: admitted.checkpoint,
|
|
149
|
+
lastCommittedActivationId: admitted.lastCommittedActivationId,
|
|
150
|
+
forkedFrom: session.forkedFrom,
|
|
151
|
+
});
|
|
152
|
+
session.nextRevisionNumber += 1;
|
|
153
|
+
session.head = result;
|
|
154
|
+
if (admitted.commitId !== undefined) {
|
|
155
|
+
state.commits.push({
|
|
156
|
+
sessionId: admitted.sessionId,
|
|
157
|
+
commitId: admitted.commitId,
|
|
158
|
+
input: admitted,
|
|
159
|
+
result,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return result;
|
|
163
|
+
});
|
|
164
|
+
await assertCheckpointReadable(this.objectStore, result.checkpoint);
|
|
165
|
+
return copyCommittedSessionRevision(result);
|
|
166
|
+
}
|
|
167
|
+
async claimFork(input) {
|
|
168
|
+
const admitted = admitClaimForkInput(input);
|
|
169
|
+
const state = await this.readState();
|
|
170
|
+
const existing = findFork(state, admitted.forkId);
|
|
171
|
+
if (existing)
|
|
172
|
+
return reconcileForkClaim(existing, admitted);
|
|
173
|
+
if (admitted.targetSessionId === admitted.source.sessionId) {
|
|
174
|
+
throw repositoryError('invalid_fork_target', 'Fork target Session must differ from its source Session');
|
|
175
|
+
}
|
|
176
|
+
const source = requireCurrentForkSource(state, admitted.source);
|
|
177
|
+
const sourceCheckpoint = admitStoredCheckpoint(source.head.checkpoint);
|
|
178
|
+
await assertCheckpointReadable(this.objectStore, sourceCheckpoint);
|
|
179
|
+
return this.mutate((latest) => {
|
|
180
|
+
const raced = findFork(latest, admitted.forkId);
|
|
181
|
+
if (raced)
|
|
182
|
+
return reconcileForkClaim(raced, admitted);
|
|
183
|
+
const stillCurrent = requireCurrentForkSource(latest, admitted.source);
|
|
184
|
+
const pending = {
|
|
185
|
+
state: 'pending',
|
|
186
|
+
forkId: admitted.forkId,
|
|
187
|
+
source: admitted.source,
|
|
188
|
+
sourceAgentId: stillCurrent.agentId,
|
|
189
|
+
sourceCheckpoint,
|
|
190
|
+
targetSessionId: admitted.targetSessionId,
|
|
191
|
+
};
|
|
192
|
+
latest.forks.push(pending);
|
|
193
|
+
return copyForkOperation(pending);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async completeFork(input) {
|
|
197
|
+
const forkId = requireIdentifier(input?.forkId, 'Fork identity');
|
|
198
|
+
const state = await this.readState();
|
|
199
|
+
const operation = findFork(state, forkId);
|
|
200
|
+
if (!operation)
|
|
201
|
+
throw repositoryError('idempotency_conflict', 'Fork identity was not claimed');
|
|
202
|
+
if (operation.state === 'completed')
|
|
203
|
+
return copyCompletedForkOperation(operation);
|
|
204
|
+
const target = requireValidForkTarget(state, operation);
|
|
205
|
+
await assertCheckpointReadable(this.objectStore, target.createdRevision.checkpoint);
|
|
206
|
+
return this.mutate((latest) => {
|
|
207
|
+
const current = findFork(latest, forkId);
|
|
208
|
+
if (!current)
|
|
209
|
+
throw repositoryError('idempotency_conflict', 'Fork identity was not claimed');
|
|
210
|
+
if (current.state === 'completed')
|
|
211
|
+
return copyCompletedForkOperation(current);
|
|
212
|
+
const target = requireValidForkTarget(latest, current);
|
|
213
|
+
const completed = {
|
|
214
|
+
...current,
|
|
215
|
+
state: 'completed',
|
|
216
|
+
target: copyRevisionRef(target.createdRevision.ref),
|
|
217
|
+
};
|
|
218
|
+
replaceFork(latest, completed);
|
|
219
|
+
return copyCompletedForkOperation(completed);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
async readState() {
|
|
223
|
+
try {
|
|
224
|
+
const bytes = await readFile(this.statePath);
|
|
225
|
+
return decodeState(bytes);
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (isNodeError(error, 'ENOENT'))
|
|
229
|
+
return emptyState();
|
|
230
|
+
if (error instanceof SessionRepositoryError)
|
|
231
|
+
throw error;
|
|
232
|
+
throw repositoryError('io_failure', 'Local Session Repository could not read state', error);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
async mutate(operation) {
|
|
236
|
+
await mkdir(dirname(this.statePath), { recursive: true, mode: 0o700 });
|
|
237
|
+
try {
|
|
238
|
+
// The native lease is released on process death, allowing the next
|
|
239
|
+
// writer to reclaim an ownerless marker without stealing a live lock.
|
|
240
|
+
return await withProcessLifetimeFileUpdateLock(this.statePath, async () => {
|
|
241
|
+
const state = await this.readState();
|
|
242
|
+
const result = operation(state);
|
|
243
|
+
await writeStateAtomically(this.statePath, state);
|
|
244
|
+
return result;
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
if (error instanceof SessionRepositoryError)
|
|
249
|
+
throw error;
|
|
250
|
+
throw repositoryError('io_failure', 'Local Session Repository could not update state', error);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
class FileImmutableObjectStore {
|
|
255
|
+
objectsRoot;
|
|
256
|
+
storageRoot;
|
|
257
|
+
constructor(objectsRoot, storageRoot) {
|
|
258
|
+
this.objectsRoot = objectsRoot;
|
|
259
|
+
this.storageRoot = storageRoot;
|
|
260
|
+
}
|
|
261
|
+
async publish(input) {
|
|
262
|
+
const admitted = admitImmutableObjectInput(input);
|
|
263
|
+
const ref = immutableObjectRef({
|
|
264
|
+
objectRef: localObjectRef(admitted.digest, admitted.mediaType),
|
|
265
|
+
digest: admitted.digest,
|
|
266
|
+
bytes: admitted.bytes,
|
|
267
|
+
mediaType: admitted.mediaType,
|
|
268
|
+
});
|
|
269
|
+
const destination = objectPath(this.objectsRoot, ref);
|
|
270
|
+
await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
|
271
|
+
const temporary = `${destination}.${randomUUID()}.tmp`;
|
|
272
|
+
try {
|
|
273
|
+
await writePublishedObject(admitted, temporary);
|
|
274
|
+
try {
|
|
275
|
+
await linkNoReplace(temporary, destination);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (!isNodeError(error, 'EEXIST'))
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
// An EEXIST result means another writer published the same immutable
|
|
282
|
+
// name. It is not readable until that writer's directory chain has a
|
|
283
|
+
// durability barrier too, so both paths wait for one before returning.
|
|
284
|
+
await syncDirectoryChain(dirname(destination), this.storageRoot);
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
throw normalizeFileError(error, 'Immutable object publication failed');
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
await rm(temporary, { force: true }).catch(() => { });
|
|
291
|
+
}
|
|
292
|
+
await this.assertReadable(ref);
|
|
293
|
+
return ref;
|
|
294
|
+
}
|
|
295
|
+
async assertReadable(input) {
|
|
296
|
+
const ref = admitImmutableObjectRef(input);
|
|
297
|
+
if (ref.objectRef !== localObjectRef(ref.digest, ref.mediaType)) {
|
|
298
|
+
throw repositoryError('integrity_mismatch', 'Immutable object reference is not canonical');
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
await assertFileMatchesImmutableRef(objectPath(this.objectsRoot, ref), ref);
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (error instanceof SessionRepositoryError)
|
|
305
|
+
throw error;
|
|
306
|
+
if (isNodeError(error, 'ENOENT')) {
|
|
307
|
+
throw repositoryError('object_not_found', 'Immutable object was not found');
|
|
308
|
+
}
|
|
309
|
+
throw repositoryError('io_failure', 'Immutable object could not be read', error);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
async materialize(input) {
|
|
313
|
+
const request = admitImmutableObjectMaterializationInput(input);
|
|
314
|
+
if (request.ref.objectRef !== localObjectRef(request.ref.digest, request.ref.mediaType)) {
|
|
315
|
+
throw repositoryError('integrity_mismatch', 'Immutable object reference is not canonical');
|
|
316
|
+
}
|
|
317
|
+
if (request.ref.bytes > request.maxBytes) {
|
|
318
|
+
throw repositoryError('quota_exceeded', 'Immutable object exceeds materialization byte limit');
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
// Verify the retained object before creating the caller-owned file. The
|
|
322
|
+
// copy below verifies it again while streaming, so a corrupt object can
|
|
323
|
+
// never be returned merely because it changed between the two reads.
|
|
324
|
+
await this.assertReadable(request.ref);
|
|
325
|
+
await copyImmutableFile(objectPath(this.objectsRoot, request.ref), request.destination, request.ref);
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
if (error instanceof SessionRepositoryError)
|
|
329
|
+
throw error;
|
|
330
|
+
throw repositoryError('io_failure', 'Immutable object could not be materialized', error);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
function emptyState() {
|
|
335
|
+
return { schemaVersion: 1, sessions: [], commits: [], forks: [] };
|
|
336
|
+
}
|
|
337
|
+
function findSession(state, sessionId) {
|
|
338
|
+
return state.sessions.find((entry) => entry.sessionId === sessionId);
|
|
339
|
+
}
|
|
340
|
+
function findCommit(state, sessionId, commitId) {
|
|
341
|
+
return commitId === undefined
|
|
342
|
+
? undefined
|
|
343
|
+
: state.commits.find((entry) => entry.sessionId === sessionId && entry.commitId === commitId);
|
|
344
|
+
}
|
|
345
|
+
function findFork(state, forkId) {
|
|
346
|
+
return state.forks.find((entry) => entry.forkId === forkId);
|
|
347
|
+
}
|
|
348
|
+
function replaceFork(state, replacement) {
|
|
349
|
+
const index = state.forks.findIndex((entry) => entry.forkId === replacement.forkId);
|
|
350
|
+
if (index < 0)
|
|
351
|
+
throw repositoryError('idempotency_conflict', 'Fork identity was not claimed');
|
|
352
|
+
state.forks[index] = replacement;
|
|
353
|
+
}
|
|
354
|
+
function requireCurrentForkSource(state, source) {
|
|
355
|
+
const session = findSession(state, source.sessionId);
|
|
356
|
+
if (!session || session.head.ref.revision !== source.revision) {
|
|
357
|
+
throw repositoryError('source_revision_not_available', 'Fork source Session revision is not available');
|
|
358
|
+
}
|
|
359
|
+
return session;
|
|
360
|
+
}
|
|
361
|
+
function requireValidForkTarget(state, operation) {
|
|
362
|
+
const target = findSession(state, operation.targetSessionId);
|
|
363
|
+
if (!target)
|
|
364
|
+
throw repositoryError('session_not_found', 'Fork target Session was not found');
|
|
365
|
+
if (target.agentId !== operation.sourceAgentId) {
|
|
366
|
+
throw repositoryError('fork_agent_mismatch', 'Fork target Agent does not match its source Agent');
|
|
367
|
+
}
|
|
368
|
+
if (target.createdByForkId !== operation.forkId ||
|
|
369
|
+
!target.forkedFrom ||
|
|
370
|
+
!sameRevisionRef(target.forkedFrom, operation.source)) {
|
|
371
|
+
throw repositoryError('idempotency_conflict', 'Fork target was created by another operation');
|
|
372
|
+
}
|
|
373
|
+
return target;
|
|
374
|
+
}
|
|
375
|
+
function assertPendingForkCreate(state, input) {
|
|
376
|
+
const operation = input.createdByForkId === undefined ? undefined : findFork(state, input.createdByForkId);
|
|
377
|
+
if (!operation ||
|
|
378
|
+
operation.state !== 'pending' ||
|
|
379
|
+
operation.targetSessionId !== input.sessionId ||
|
|
380
|
+
!input.forkedFrom ||
|
|
381
|
+
!sameRevisionRef(operation.source, input.forkedFrom)) {
|
|
382
|
+
throw repositoryError('idempotency_conflict', 'Fork target does not match its claimed operation');
|
|
383
|
+
}
|
|
384
|
+
if (operation.sourceAgentId !== input.agentId) {
|
|
385
|
+
throw repositoryError('fork_agent_mismatch', 'Fork target Agent must match its source Agent');
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
function reconcileExistingSessionCreate(existing, input) {
|
|
389
|
+
if (input.createdByForkId !== undefined &&
|
|
390
|
+
existing.createdByForkId === input.createdByForkId &&
|
|
391
|
+
existing.agentId === input.agentId &&
|
|
392
|
+
sameStoredCheckpoint(existing.createdRevision.checkpoint, input.checkpoint) &&
|
|
393
|
+
existing.createdRevision.lastCommittedActivationId === input.lastCommittedActivationId &&
|
|
394
|
+
sameOptionalRevisionRef(existing.forkedFrom, input.forkedFrom)) {
|
|
395
|
+
return existing.createdRevision;
|
|
396
|
+
}
|
|
397
|
+
throw repositoryError('session_already_exists', 'Cloud Session already exists');
|
|
398
|
+
}
|
|
399
|
+
function reconcileForkClaim(operation, input) {
|
|
400
|
+
if (operation.targetSessionId !== input.targetSessionId ||
|
|
401
|
+
!sameRevisionRef(operation.source, input.source)) {
|
|
402
|
+
throw repositoryError('idempotency_conflict', 'Fork identity was reused with different input');
|
|
403
|
+
}
|
|
404
|
+
return copyForkOperation(operation);
|
|
405
|
+
}
|
|
406
|
+
function assertSameCommitInput(left, right) {
|
|
407
|
+
if (left.sessionId !== right.sessionId ||
|
|
408
|
+
left.expectedRevision !== right.expectedRevision ||
|
|
409
|
+
!sameStoredCheckpoint(left.checkpoint, right.checkpoint) ||
|
|
410
|
+
left.lastCommittedActivationId !== right.lastCommittedActivationId ||
|
|
411
|
+
left.commitId !== right.commitId) {
|
|
412
|
+
throw repositoryError('idempotency_conflict', 'Commit identity was reused with different input');
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
async function assertCheckpointReadable(objectStore, checkpoint) {
|
|
416
|
+
const admitted = admitStoredCheckpoint(checkpoint);
|
|
417
|
+
try {
|
|
418
|
+
await objectStore.assertReadable(admitted.manifest);
|
|
419
|
+
await objectStore.assertReadable(admitted.value.compatibilityBundle);
|
|
420
|
+
}
|
|
421
|
+
catch (error) {
|
|
422
|
+
if (error instanceof SessionRepositoryError)
|
|
423
|
+
throw error;
|
|
424
|
+
throw repositoryError('io_failure', 'Immutable Object Store operation failed', error);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
function admitCommitSessionRevisionInput(input) {
|
|
428
|
+
if (!isRecord(input))
|
|
429
|
+
throw new TypeError('Session commit input must be an object');
|
|
430
|
+
return {
|
|
431
|
+
sessionId: requireIdentifier(input.sessionId, 'Session identity'),
|
|
432
|
+
expectedRevision: requireIdentifier(input.expectedRevision, 'Expected revision'),
|
|
433
|
+
checkpoint: admitStoredCheckpoint(input.checkpoint),
|
|
434
|
+
...(input.lastCommittedActivationId === undefined
|
|
435
|
+
? {}
|
|
436
|
+
: {
|
|
437
|
+
lastCommittedActivationId: requireIdentifier(input.lastCommittedActivationId, 'Activation identity'),
|
|
438
|
+
}),
|
|
439
|
+
...(input.commitId === undefined
|
|
440
|
+
? {}
|
|
441
|
+
: { commitId: requireIdentifier(input.commitId, 'Commit identity') }),
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
function admitCreateSessionInput(input) {
|
|
445
|
+
if (!isRecord(input))
|
|
446
|
+
throw new TypeError('Session creation input must be an object');
|
|
447
|
+
const forkedFrom = input.forkedFrom === undefined ? undefined : admitRevisionRef(input.forkedFrom, 'Fork source');
|
|
448
|
+
const createdByForkId = input.createdByForkId === undefined
|
|
449
|
+
? undefined
|
|
450
|
+
: requireIdentifier(input.createdByForkId, 'Fork identity');
|
|
451
|
+
if ((forkedFrom === undefined) !== (createdByForkId === undefined)) {
|
|
452
|
+
throw new TypeError('Fork lineage and Fork identity must be supplied together');
|
|
453
|
+
}
|
|
454
|
+
if (createdByForkId !== undefined && input.lastCommittedActivationId !== undefined) {
|
|
455
|
+
throw new TypeError('Fork-created Session must not carry an Activation identity');
|
|
456
|
+
}
|
|
457
|
+
return {
|
|
458
|
+
sessionId: requireIdentifier(input.sessionId, 'Session identity'),
|
|
459
|
+
agentId: requireIdentifier(input.agentId, 'Agent identity'),
|
|
460
|
+
checkpoint: admitStoredCheckpoint(input.checkpoint),
|
|
461
|
+
...(input.lastCommittedActivationId === undefined
|
|
462
|
+
? {}
|
|
463
|
+
: {
|
|
464
|
+
lastCommittedActivationId: requireIdentifier(input.lastCommittedActivationId, 'Activation identity'),
|
|
465
|
+
}),
|
|
466
|
+
...(forkedFrom === undefined ? {} : { forkedFrom }),
|
|
467
|
+
...(createdByForkId === undefined ? {} : { createdByForkId }),
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
function admitClaimForkInput(input) {
|
|
471
|
+
if (!isRecord(input))
|
|
472
|
+
throw new TypeError('Fork claim input must be an object');
|
|
473
|
+
return {
|
|
474
|
+
forkId: requireIdentifier(input.forkId, 'Fork identity'),
|
|
475
|
+
source: admitRevisionRef(input.source, 'Fork source'),
|
|
476
|
+
targetSessionId: requireIdentifier(input.targetSessionId, 'Fork target Session identity'),
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
function admitStoredCheckpoint(input) {
|
|
480
|
+
if (!isRecord(input))
|
|
481
|
+
throw new TypeError('Stored Session checkpoint must be an object');
|
|
482
|
+
const manifest = admitImmutableObjectRef(input.manifest);
|
|
483
|
+
if (!isRecord(input.value) || input.value.schemaVersion !== 1) {
|
|
484
|
+
throw new TypeError('Session checkpoint Manifest schema version must be 1');
|
|
485
|
+
}
|
|
486
|
+
const value = createSessionCheckpointManifestV1(admitImmutableObjectRef(input.value.compatibilityBundle));
|
|
487
|
+
if (manifest.mediaType !== SESSION_CHECKPOINT_MANIFEST_MEDIA_TYPE) {
|
|
488
|
+
throw new TypeError('Session checkpoint Manifest has an unsupported media type');
|
|
489
|
+
}
|
|
490
|
+
const bytes = encodeSessionCheckpointManifestV1(value);
|
|
491
|
+
if (manifest.digest !== digestBytes(bytes) || manifest.bytes !== bytes.byteLength) {
|
|
492
|
+
throw repositoryError('integrity_mismatch', 'Manifest value does not match its reference');
|
|
493
|
+
}
|
|
494
|
+
return { manifest, value };
|
|
495
|
+
}
|
|
496
|
+
function admitImmutableObjectInput(input) {
|
|
497
|
+
if (!isRecord(input) || !isSha256Digest(input.digest) || !isByteCount(input.bytes)) {
|
|
498
|
+
throw new TypeError('Immutable object input is invalid');
|
|
499
|
+
}
|
|
500
|
+
const mediaType = requireIdentifier(input.mediaType, 'Immutable object media type');
|
|
501
|
+
if (!isRecord(input.source))
|
|
502
|
+
throw new TypeError('Immutable object source is invalid');
|
|
503
|
+
if (input.source.kind === 'file') {
|
|
504
|
+
return {
|
|
505
|
+
...input,
|
|
506
|
+
mediaType,
|
|
507
|
+
source: {
|
|
508
|
+
kind: 'file',
|
|
509
|
+
path: requireIdentifier(input.source.path, 'Object source path', MAX_OBJECT_REF_LENGTH),
|
|
510
|
+
},
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
if (input.source.kind === 'bytes' && input.source.value instanceof Uint8Array) {
|
|
514
|
+
return {
|
|
515
|
+
...input,
|
|
516
|
+
mediaType,
|
|
517
|
+
source: { kind: 'bytes', value: Uint8Array.from(input.source.value) },
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
throw new TypeError('Immutable object source is invalid');
|
|
521
|
+
}
|
|
522
|
+
function admitImmutableObjectMaterializationInput(input) {
|
|
523
|
+
if (!isRecord(input)) {
|
|
524
|
+
throw new TypeError('Immutable object materialization input must be an object');
|
|
525
|
+
}
|
|
526
|
+
if (!isByteCount(input.maxBytes)) {
|
|
527
|
+
throw new TypeError('Immutable object materialization byte limit must be a non-negative safe integer');
|
|
528
|
+
}
|
|
529
|
+
return {
|
|
530
|
+
ref: admitImmutableObjectRef(input.ref),
|
|
531
|
+
destination: requireIdentifier(input.destination, 'Immutable object materialization destination', MAX_OBJECT_REF_LENGTH),
|
|
532
|
+
maxBytes: input.maxBytes,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function admitImmutableObjectRef(input) {
|
|
536
|
+
if (!isRecord(input) || !isSha256Digest(input.digest) || !isByteCount(input.bytes)) {
|
|
537
|
+
throw new TypeError('Immutable object reference is invalid');
|
|
538
|
+
}
|
|
539
|
+
return immutableObjectRef({
|
|
540
|
+
objectRef: requireIdentifier(input.objectRef, 'Immutable object reference', MAX_OBJECT_REF_LENGTH),
|
|
541
|
+
digest: input.digest,
|
|
542
|
+
bytes: input.bytes,
|
|
543
|
+
mediaType: requireIdentifier(input.mediaType, 'Immutable object media type'),
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
function admitRevisionRef(input, label) {
|
|
547
|
+
if (!isRecord(input))
|
|
548
|
+
throw new TypeError(`${label} must be an object`);
|
|
549
|
+
return copyRevisionRef({
|
|
550
|
+
sessionId: requireIdentifier(input.sessionId, `${label} Session identity`),
|
|
551
|
+
revision: requireIdentifier(input.revision, `${label} revision`),
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
function committedRevision(input) {
|
|
555
|
+
return {
|
|
556
|
+
ref: copyRevisionRef({ sessionId: input.sessionId, revision: input.revision }),
|
|
557
|
+
agentId: input.agentId,
|
|
558
|
+
checkpoint: admitStoredCheckpoint(input.checkpoint),
|
|
559
|
+
...(input.lastCommittedActivationId === undefined
|
|
560
|
+
? {}
|
|
561
|
+
: { lastCommittedActivationId: input.lastCommittedActivationId }),
|
|
562
|
+
...(input.forkedFrom === undefined ? {} : { forkedFrom: copyRevisionRef(input.forkedFrom) }),
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
function copyCommittedSessionRevision(input) {
|
|
566
|
+
return committedRevision({
|
|
567
|
+
sessionId: input.ref.sessionId,
|
|
568
|
+
revision: input.ref.revision,
|
|
569
|
+
agentId: input.agentId,
|
|
570
|
+
checkpoint: input.checkpoint,
|
|
571
|
+
...(input.lastCommittedActivationId === undefined
|
|
572
|
+
? {}
|
|
573
|
+
: { lastCommittedActivationId: input.lastCommittedActivationId }),
|
|
574
|
+
...(input.forkedFrom === undefined ? {} : { forkedFrom: input.forkedFrom }),
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
function immutableObjectRef(input) {
|
|
578
|
+
return {
|
|
579
|
+
objectRef: input.objectRef,
|
|
580
|
+
digest: input.digest,
|
|
581
|
+
bytes: input.bytes,
|
|
582
|
+
mediaType: input.mediaType,
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
function copyRevisionRef(input) {
|
|
586
|
+
return { sessionId: input.sessionId, revision: input.revision };
|
|
587
|
+
}
|
|
588
|
+
function copyForkOperation(input) {
|
|
589
|
+
return input.state === 'pending'
|
|
590
|
+
? {
|
|
591
|
+
state: 'pending',
|
|
592
|
+
forkId: input.forkId,
|
|
593
|
+
source: copyRevisionRef(input.source),
|
|
594
|
+
sourceAgentId: input.sourceAgentId,
|
|
595
|
+
sourceCheckpoint: admitStoredCheckpoint(input.sourceCheckpoint),
|
|
596
|
+
targetSessionId: input.targetSessionId,
|
|
597
|
+
}
|
|
598
|
+
: copyCompletedForkOperation(input);
|
|
599
|
+
}
|
|
600
|
+
function copyCompletedForkOperation(input) {
|
|
601
|
+
return {
|
|
602
|
+
state: 'completed',
|
|
603
|
+
forkId: input.forkId,
|
|
604
|
+
source: copyRevisionRef(input.source),
|
|
605
|
+
sourceAgentId: input.sourceAgentId,
|
|
606
|
+
sourceCheckpoint: admitStoredCheckpoint(input.sourceCheckpoint),
|
|
607
|
+
targetSessionId: input.targetSessionId,
|
|
608
|
+
target: copyRevisionRef(input.target),
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
function sameStoredCheckpoint(left, right) {
|
|
612
|
+
return (sameImmutableObjectRef(left.manifest, right.manifest) &&
|
|
613
|
+
sameImmutableObjectRef(left.value.compatibilityBundle, right.value.compatibilityBundle));
|
|
614
|
+
}
|
|
615
|
+
function sameImmutableObjectRef(left, right) {
|
|
616
|
+
return (left.objectRef === right.objectRef &&
|
|
617
|
+
left.digest === right.digest &&
|
|
618
|
+
left.bytes === right.bytes &&
|
|
619
|
+
left.mediaType === right.mediaType);
|
|
620
|
+
}
|
|
621
|
+
function sameRevisionRef(left, right) {
|
|
622
|
+
return left.sessionId === right.sessionId && left.revision === right.revision;
|
|
623
|
+
}
|
|
624
|
+
function sameOptionalRevisionRef(left, right) {
|
|
625
|
+
return left === undefined || right === undefined ? left === right : sameRevisionRef(left, right);
|
|
626
|
+
}
|
|
627
|
+
async function writePublishedObject(input, destination) {
|
|
628
|
+
if (input.source.kind === 'bytes') {
|
|
629
|
+
const bytes = Uint8Array.from(input.source.value);
|
|
630
|
+
assertImmutableBytesMatch(bytes, input.digest, input.bytes);
|
|
631
|
+
await writeNewFile(destination, async (handle) => writeAll(handle, bytes));
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
await copyImmutableFile(input.source.path, destination, {
|
|
635
|
+
digest: input.digest,
|
|
636
|
+
bytes: input.bytes,
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Copies and verifies in chunks. The supplied reference is deliberately the
|
|
641
|
+
* bound: a malicious or changing source can never make this adapter retain an
|
|
642
|
+
* unbounded in-memory buffer or publish more bytes than it declared.
|
|
643
|
+
*/
|
|
644
|
+
async function copyImmutableFile(source, destination, ref) {
|
|
645
|
+
await writeNewFile(destination, async (handle) => {
|
|
646
|
+
const digest = createHash('sha256');
|
|
647
|
+
let bytes = 0;
|
|
648
|
+
for await (const rawChunk of createReadStream(source)) {
|
|
649
|
+
const chunk = Buffer.from(rawChunk);
|
|
650
|
+
bytes += chunk.byteLength;
|
|
651
|
+
if (bytes > ref.bytes) {
|
|
652
|
+
throw repositoryError('integrity_mismatch', 'Immutable object bytes exceed declared metadata');
|
|
653
|
+
}
|
|
654
|
+
digest.update(chunk);
|
|
655
|
+
await writeAll(handle, chunk);
|
|
656
|
+
}
|
|
657
|
+
assertImmutableDigestMatch(bytes, digest.digest('hex'), ref.bytes, ref.digest);
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
async function assertFileMatchesImmutableRef(path, ref) {
|
|
661
|
+
const digest = createHash('sha256');
|
|
662
|
+
let bytes = 0;
|
|
663
|
+
for await (const rawChunk of createReadStream(path)) {
|
|
664
|
+
const chunk = Buffer.from(rawChunk);
|
|
665
|
+
bytes += chunk.byteLength;
|
|
666
|
+
if (bytes > ref.bytes) {
|
|
667
|
+
throw repositoryError('integrity_mismatch', 'Immutable object bytes no longer match metadata');
|
|
668
|
+
}
|
|
669
|
+
digest.update(chunk);
|
|
670
|
+
}
|
|
671
|
+
assertImmutableDigestMatch(bytes, digest.digest('hex'), ref.bytes, ref.digest);
|
|
672
|
+
}
|
|
673
|
+
async function writeNewFile(path, writer) {
|
|
674
|
+
let handle;
|
|
675
|
+
try {
|
|
676
|
+
handle = await open(path, 'wx', 0o600);
|
|
677
|
+
await writer(handle);
|
|
678
|
+
await handle.sync();
|
|
679
|
+
}
|
|
680
|
+
catch (error) {
|
|
681
|
+
if (handle) {
|
|
682
|
+
await handle.close().catch(() => { });
|
|
683
|
+
handle = undefined;
|
|
684
|
+
await rm(path, { force: true }).catch(() => { });
|
|
685
|
+
}
|
|
686
|
+
throw error;
|
|
687
|
+
}
|
|
688
|
+
finally {
|
|
689
|
+
if (handle)
|
|
690
|
+
await handle.close();
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
async function writeAll(handle, value) {
|
|
694
|
+
const bytes = Buffer.from(value);
|
|
695
|
+
let offset = 0;
|
|
696
|
+
while (offset < bytes.byteLength) {
|
|
697
|
+
const result = await handle.write(bytes, offset, bytes.byteLength - offset, null);
|
|
698
|
+
if (result.bytesWritten <= 0) {
|
|
699
|
+
throw repositoryError('io_failure', 'Immutable object write made no progress');
|
|
700
|
+
}
|
|
701
|
+
offset += result.bytesWritten;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
function assertImmutableBytesMatch(bytes, expectedDigest, expectedBytes) {
|
|
705
|
+
if (bytes.byteLength !== expectedBytes || digestBytes(bytes) !== expectedDigest) {
|
|
706
|
+
throw repositoryError('integrity_mismatch', 'Immutable object bytes do not match declared metadata');
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
function assertImmutableDigestMatch(actualBytes, digestHex, expectedBytes, expectedDigest) {
|
|
710
|
+
const actualDigest = `sha256:${digestHex}`;
|
|
711
|
+
if (actualBytes !== expectedBytes || actualDigest !== expectedDigest) {
|
|
712
|
+
throw repositoryError('integrity_mismatch', 'Immutable object bytes no longer match metadata');
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
function localObjectRef(digest, mediaType) {
|
|
716
|
+
return `maka-local-object://v1/${createHash('sha256').update(`${digest}\u0000${mediaType}`).digest('hex')}`;
|
|
717
|
+
}
|
|
718
|
+
function objectPath(objectsRoot, ref) {
|
|
719
|
+
const id = ref.objectRef.slice('maka-local-object://v1/'.length);
|
|
720
|
+
return join(objectsRoot, id.slice(0, 2), id);
|
|
721
|
+
}
|
|
722
|
+
async function linkNoReplace(source, destination) {
|
|
723
|
+
const { link } = await import('node:fs/promises');
|
|
724
|
+
await link(source, destination);
|
|
725
|
+
}
|
|
726
|
+
async function writeStateAtomically(path, state) {
|
|
727
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
728
|
+
const bytes = Buffer.from(`${JSON.stringify(state)}\n`, 'utf8');
|
|
729
|
+
try {
|
|
730
|
+
const handle = await open(temporary, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
|
|
731
|
+
try {
|
|
732
|
+
await handle.writeFile(bytes);
|
|
733
|
+
await handle.sync();
|
|
734
|
+
}
|
|
735
|
+
finally {
|
|
736
|
+
await handle.close();
|
|
737
|
+
}
|
|
738
|
+
await rename(temporary, path);
|
|
739
|
+
await syncDirectory(dirname(path));
|
|
740
|
+
}
|
|
741
|
+
finally {
|
|
742
|
+
await rm(temporary, { force: true }).catch(() => { });
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
function decodeState(bytes) {
|
|
746
|
+
let parsed;
|
|
747
|
+
try {
|
|
748
|
+
parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
749
|
+
}
|
|
750
|
+
catch (error) {
|
|
751
|
+
throw repositoryError('integrity_mismatch', 'Local Session Repository state is invalid JSON', error);
|
|
752
|
+
}
|
|
753
|
+
if (!isRecord(parsed) ||
|
|
754
|
+
parsed.schemaVersion !== 1 ||
|
|
755
|
+
!Array.isArray(parsed.sessions) ||
|
|
756
|
+
!Array.isArray(parsed.commits) ||
|
|
757
|
+
!Array.isArray(parsed.forks)) {
|
|
758
|
+
throw repositoryError('integrity_mismatch', 'Local Session Repository state schema is invalid');
|
|
759
|
+
}
|
|
760
|
+
try {
|
|
761
|
+
const state = {
|
|
762
|
+
schemaVersion: 1,
|
|
763
|
+
sessions: parsed.sessions.map(decodeSession),
|
|
764
|
+
commits: parsed.commits.map(decodeCommit),
|
|
765
|
+
forks: parsed.forks.map(decodeFork),
|
|
766
|
+
};
|
|
767
|
+
assertUnique(state.sessions, (entry) => entry.sessionId, 'Session identity');
|
|
768
|
+
assertUnique(state.commits, (entry) => JSON.stringify([entry.sessionId, entry.commitId]), 'Commit identity');
|
|
769
|
+
assertUnique(state.forks, (entry) => entry.forkId, 'Fork identity');
|
|
770
|
+
assertPersistentStateConsistency(state);
|
|
771
|
+
return state;
|
|
772
|
+
}
|
|
773
|
+
catch (error) {
|
|
774
|
+
if (error instanceof SessionRepositoryError)
|
|
775
|
+
throw error;
|
|
776
|
+
throw repositoryError('integrity_mismatch', 'Local Session Repository state is invalid', error);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
function decodeSession(value) {
|
|
780
|
+
if (!isRecord(value))
|
|
781
|
+
throw new TypeError('Session state is invalid');
|
|
782
|
+
const sessionId = requireIdentifier(value.sessionId, 'Session identity');
|
|
783
|
+
const agentId = requireIdentifier(value.agentId, 'Agent identity');
|
|
784
|
+
const forkedFrom = value.forkedFrom === undefined
|
|
785
|
+
? undefined
|
|
786
|
+
: admitRevisionRef(value.forkedFrom, 'Fork source');
|
|
787
|
+
const createdByForkId = value.createdByForkId === undefined
|
|
788
|
+
? undefined
|
|
789
|
+
: requireIdentifier(value.createdByForkId, 'Fork identity');
|
|
790
|
+
if ((forkedFrom === undefined) !== (createdByForkId === undefined)) {
|
|
791
|
+
throw new TypeError('Session Fork lineage and Fork identity must be supplied together');
|
|
792
|
+
}
|
|
793
|
+
const head = decodeCommitted(value.head);
|
|
794
|
+
const createdRevision = decodeCommitted(value.createdRevision);
|
|
795
|
+
if (head.ref.sessionId !== sessionId ||
|
|
796
|
+
head.agentId !== agentId ||
|
|
797
|
+
createdRevision.ref.sessionId !== sessionId ||
|
|
798
|
+
createdRevision.agentId !== agentId) {
|
|
799
|
+
throw new TypeError('Session state identity binding is invalid');
|
|
800
|
+
}
|
|
801
|
+
return {
|
|
802
|
+
sessionId,
|
|
803
|
+
agentId,
|
|
804
|
+
head,
|
|
805
|
+
nextRevisionNumber: requireRevisionNumber(value.nextRevisionNumber),
|
|
806
|
+
...(forkedFrom === undefined ? {} : { forkedFrom }),
|
|
807
|
+
...(createdByForkId === undefined ? {} : { createdByForkId }),
|
|
808
|
+
createdRevision,
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
function decodeCommit(value) {
|
|
812
|
+
if (!isRecord(value))
|
|
813
|
+
throw new TypeError('Commit state is invalid');
|
|
814
|
+
const input = admitCommitSessionRevisionInput(value.input);
|
|
815
|
+
if (input.commitId === undefined)
|
|
816
|
+
throw new TypeError('Commit state lacks identity');
|
|
817
|
+
const sessionId = requireIdentifier(value.sessionId, 'Session identity');
|
|
818
|
+
const commitId = requireIdentifier(value.commitId, 'Commit identity');
|
|
819
|
+
const result = decodeCommitted(value.result);
|
|
820
|
+
if (input.sessionId !== sessionId ||
|
|
821
|
+
input.commitId !== commitId ||
|
|
822
|
+
result.ref.sessionId !== sessionId) {
|
|
823
|
+
throw new TypeError('Commit state identity binding is invalid');
|
|
824
|
+
}
|
|
825
|
+
return {
|
|
826
|
+
sessionId,
|
|
827
|
+
commitId,
|
|
828
|
+
input,
|
|
829
|
+
result,
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
function decodeFork(value) {
|
|
833
|
+
if (!isRecord(value))
|
|
834
|
+
throw new TypeError('Fork state is invalid');
|
|
835
|
+
const base = {
|
|
836
|
+
forkId: requireIdentifier(value.forkId, 'Fork identity'),
|
|
837
|
+
source: admitRevisionRef(value.source, 'Fork source'),
|
|
838
|
+
sourceAgentId: requireIdentifier(value.sourceAgentId, 'Fork source Agent identity'),
|
|
839
|
+
sourceCheckpoint: admitStoredCheckpoint(value.sourceCheckpoint),
|
|
840
|
+
targetSessionId: requireIdentifier(value.targetSessionId, 'Fork target Session identity'),
|
|
841
|
+
};
|
|
842
|
+
if (value.state === 'pending')
|
|
843
|
+
return { state: 'pending', ...base };
|
|
844
|
+
if (value.state === 'completed') {
|
|
845
|
+
return {
|
|
846
|
+
state: 'completed',
|
|
847
|
+
...base,
|
|
848
|
+
target: admitRevisionRef(value.target, 'Fork target'),
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
throw new TypeError('Fork state is invalid');
|
|
852
|
+
}
|
|
853
|
+
function decodeCommitted(value) {
|
|
854
|
+
if (!isRecord(value))
|
|
855
|
+
throw new TypeError('Committed revision is invalid');
|
|
856
|
+
return committedRevision({
|
|
857
|
+
sessionId: admitRevisionRef(value.ref, 'Session revision reference')
|
|
858
|
+
.sessionId,
|
|
859
|
+
revision: admitRevisionRef(value.ref, 'Session revision reference')
|
|
860
|
+
.revision,
|
|
861
|
+
agentId: requireIdentifier(value.agentId, 'Agent identity'),
|
|
862
|
+
checkpoint: admitStoredCheckpoint(value.checkpoint),
|
|
863
|
+
...(value.lastCommittedActivationId === undefined
|
|
864
|
+
? {}
|
|
865
|
+
: {
|
|
866
|
+
lastCommittedActivationId: requireIdentifier(value.lastCommittedActivationId, 'Activation identity'),
|
|
867
|
+
}),
|
|
868
|
+
...(value.forkedFrom === undefined
|
|
869
|
+
? {}
|
|
870
|
+
: { forkedFrom: admitRevisionRef(value.forkedFrom, 'Fork source') }),
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
function requireRevisionNumber(value) {
|
|
874
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 2)
|
|
875
|
+
throw new TypeError('Next revision number is invalid');
|
|
876
|
+
return value;
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* JSON syntax and individual field validation are not sufficient for the
|
|
880
|
+
* control document: the records must describe one non-contradictory Session
|
|
881
|
+
* history before any writer derives a new revision from it.
|
|
882
|
+
*/
|
|
883
|
+
function assertPersistentStateConsistency(state) {
|
|
884
|
+
for (const session of state.sessions) {
|
|
885
|
+
assertPersistentSessionConsistency(session);
|
|
886
|
+
assertPersistentCreatedForkTarget(state, session);
|
|
887
|
+
}
|
|
888
|
+
const committedRevisions = new Set();
|
|
889
|
+
for (const commit of state.commits) {
|
|
890
|
+
const session = findSession(state, commit.sessionId);
|
|
891
|
+
if (!session)
|
|
892
|
+
throw new TypeError('Commit receipt references an unknown Session');
|
|
893
|
+
const expectedRevision = revisionNumber(commit.input.expectedRevision, 'Commit expected revision');
|
|
894
|
+
const resultRevision = revisionNumber(commit.result.ref.revision, 'Commit result revision');
|
|
895
|
+
const headRevision = revisionNumber(session.head.ref.revision, 'Session head revision');
|
|
896
|
+
if (resultRevision < 2 ||
|
|
897
|
+
resultRevision > headRevision ||
|
|
898
|
+
expectedRevision + 1 !== resultRevision ||
|
|
899
|
+
commit.result.agentId !== session.agentId ||
|
|
900
|
+
!sameStoredCheckpoint(commit.input.checkpoint, commit.result.checkpoint) ||
|
|
901
|
+
commit.input.lastCommittedActivationId !== commit.result.lastCommittedActivationId ||
|
|
902
|
+
!sameOptionalRevisionRef(commit.result.forkedFrom, session.forkedFrom) ||
|
|
903
|
+
(resultRevision === headRevision &&
|
|
904
|
+
!sameCommittedSessionRevision(commit.result, session.head))) {
|
|
905
|
+
throw new TypeError('Commit receipt contradicts Session state');
|
|
906
|
+
}
|
|
907
|
+
const key = `${commit.sessionId}\u0000${commit.result.ref.revision}`;
|
|
908
|
+
if (committedRevisions.has(key))
|
|
909
|
+
throw new TypeError('Commit result revision is duplicated');
|
|
910
|
+
committedRevisions.add(key);
|
|
911
|
+
}
|
|
912
|
+
for (const fork of state.forks)
|
|
913
|
+
assertPersistentForkConsistency(state, fork);
|
|
914
|
+
}
|
|
915
|
+
function assertPersistentSessionConsistency(session) {
|
|
916
|
+
const createdRevision = revisionNumber(session.createdRevision.ref.revision, 'Session creation revision');
|
|
917
|
+
const headRevision = revisionNumber(session.head.ref.revision, 'Session head revision');
|
|
918
|
+
if (createdRevision !== 1 ||
|
|
919
|
+
headRevision >= Number.MAX_SAFE_INTEGER ||
|
|
920
|
+
session.nextRevisionNumber !== headRevision + 1 ||
|
|
921
|
+
!sameOptionalRevisionRef(session.createdRevision.forkedFrom, session.forkedFrom) ||
|
|
922
|
+
!sameOptionalRevisionRef(session.head.forkedFrom, session.forkedFrom) ||
|
|
923
|
+
(session.createdByForkId !== undefined &&
|
|
924
|
+
session.createdRevision.lastCommittedActivationId !== undefined)) {
|
|
925
|
+
throw new TypeError('Session revision sequence is inconsistent');
|
|
926
|
+
}
|
|
927
|
+
if (headRevision === 1 && !sameCommittedSessionRevision(session.head, session.createdRevision)) {
|
|
928
|
+
throw new TypeError('Session initial head contradicts creation revision');
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
function assertPersistentForkConsistency(state, fork) {
|
|
932
|
+
if (fork.source.sessionId === fork.targetSessionId) {
|
|
933
|
+
throw new TypeError('Fork target Session must differ from its source Session');
|
|
934
|
+
}
|
|
935
|
+
const source = findSession(state, fork.source.sessionId);
|
|
936
|
+
if (!source || source.agentId !== fork.sourceAgentId) {
|
|
937
|
+
throw new TypeError('Fork source Agent binding is inconsistent');
|
|
938
|
+
}
|
|
939
|
+
const target = findSession(state, fork.targetSessionId);
|
|
940
|
+
if (fork.state === 'completed') {
|
|
941
|
+
if (!target ||
|
|
942
|
+
target.agentId !== fork.sourceAgentId ||
|
|
943
|
+
target.createdByForkId !== fork.forkId ||
|
|
944
|
+
!target.forkedFrom ||
|
|
945
|
+
!sameRevisionRef(target.forkedFrom, fork.source) ||
|
|
946
|
+
!sameRevisionRef(fork.target, target.createdRevision.ref)) {
|
|
947
|
+
throw new TypeError('Completed Fork target is inconsistent');
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
function assertPersistentCreatedForkTarget(state, session) {
|
|
952
|
+
if (session.createdByForkId === undefined || session.forkedFrom === undefined)
|
|
953
|
+
return;
|
|
954
|
+
const fork = findFork(state, session.createdByForkId);
|
|
955
|
+
if (!fork ||
|
|
956
|
+
fork.targetSessionId !== session.sessionId ||
|
|
957
|
+
fork.sourceAgentId !== session.agentId ||
|
|
958
|
+
!sameRevisionRef(fork.source, session.forkedFrom)) {
|
|
959
|
+
throw new TypeError('Fork-created Session does not match its claimed operation');
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function revisionNumber(revision, label) {
|
|
963
|
+
const match = /^r([1-9][0-9]*)$/u.exec(revision);
|
|
964
|
+
if (!match)
|
|
965
|
+
throw new TypeError(`${label} is not a canonical revision`);
|
|
966
|
+
const value = Number(match[1]);
|
|
967
|
+
if (!Number.isSafeInteger(value))
|
|
968
|
+
throw new TypeError(`${label} is outside the safe range`);
|
|
969
|
+
return value;
|
|
970
|
+
}
|
|
971
|
+
function sameCommittedSessionRevision(left, right) {
|
|
972
|
+
return (sameRevisionRef(left.ref, right.ref) &&
|
|
973
|
+
left.agentId === right.agentId &&
|
|
974
|
+
sameStoredCheckpoint(left.checkpoint, right.checkpoint) &&
|
|
975
|
+
left.lastCommittedActivationId === right.lastCommittedActivationId &&
|
|
976
|
+
sameOptionalRevisionRef(left.forkedFrom, right.forkedFrom));
|
|
977
|
+
}
|
|
978
|
+
function assertUnique(values, key, label) {
|
|
979
|
+
const seen = new Set();
|
|
980
|
+
for (const value of values) {
|
|
981
|
+
const current = key(value);
|
|
982
|
+
if (seen.has(current))
|
|
983
|
+
throw new TypeError(`${label} is duplicated`);
|
|
984
|
+
seen.add(current);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
function requireIdentifier(value, label, maximumLength = MAX_IDENTIFIER_LENGTH) {
|
|
988
|
+
if (!isNonEmptyUnicodeString(value) || value.length > maximumLength) {
|
|
989
|
+
throw new TypeError(`${label} must be a bounded non-empty Unicode string`);
|
|
990
|
+
}
|
|
991
|
+
return value;
|
|
992
|
+
}
|
|
993
|
+
function isByteCount(value) {
|
|
994
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
995
|
+
}
|
|
996
|
+
function isRecord(value) {
|
|
997
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
998
|
+
}
|
|
999
|
+
function digestBytes(value) {
|
|
1000
|
+
return `sha256:${createHash('sha256').update(value).digest('hex')}`;
|
|
1001
|
+
}
|
|
1002
|
+
function repositoryError(code, message, cause) {
|
|
1003
|
+
return new SessionRepositoryError(code, message, cause === undefined ? {} : { cause });
|
|
1004
|
+
}
|
|
1005
|
+
function normalizeFileError(error, message) {
|
|
1006
|
+
if (error instanceof SessionRepositoryError)
|
|
1007
|
+
return error;
|
|
1008
|
+
return repositoryError('io_failure', message, error);
|
|
1009
|
+
}
|
|
1010
|
+
function isNodeError(error, code) {
|
|
1011
|
+
return error instanceof Error && 'code' in error && error.code === code;
|
|
1012
|
+
}
|