code60-transmission-server 0.0.0-stage → 0.1.0-staging.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +294 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +205 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +166 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +116 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11086 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +227 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
@@ -0,0 +1,205 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { jsonCopy } from '../broker/policy.js';
3
+ import { EngineStore } from '../storage/store.js';
4
+ import { ApiError } from '../server/errors.js';
5
+ import { PublicationService } from '../server/publication.js';
6
+ const roles = ['worker', 'verifier', 'handoff'];
7
+ const sha256 = (content) => `sha256:${createHash('sha256').update(content, 'utf8').digest('hex')}`;
8
+ const relativePath = /^(?!\/)(?![A-Za-z][A-Za-z0-9+.-]*:)(?!.*\/\/)(?!.*(?:^|\/)\.{1,2}(?:\/|$))[^\\\0\r\n]+(?<!\/)$/;
9
+ const sourceIoErrors = new Set(['ENOENT', 'ENOTDIR', 'EISDIR', 'EACCES', 'EPERM', 'ELOOP', 'ESTALE', 'ENAMETOOLONG']);
10
+ /** Pin authored sources outside SQL. The core owns publishing every returned
11
+ * snapshot and its plan IDs in one transaction before it starts any agent. */
12
+ export class InstructionPins {
13
+ store;
14
+ publication;
15
+ options;
16
+ constructor(store, publication, options) {
17
+ this.store = store;
18
+ this.publication = publication;
19
+ this.options = options;
20
+ }
21
+ resolve(definition, runBindings, signal) {
22
+ // Keep this public wrapper synchronous so a SQL caller fails before even
23
+ // creating a promise, not as an escaped asynchronous SQL operation.
24
+ this.store.coordinator.assertOutsideTransaction();
25
+ const versions = new Map();
26
+ const result = definition.steps.map(step => {
27
+ const bindings = { ...definition.config?.['agent-profiles'], ...runBindings, ...step['agent-profiles'] };
28
+ const required = ['worker'];
29
+ if (step.exitCriteria.semantic?.criteria.length)
30
+ required.push('verifier');
31
+ if (step.handoffArtifact?.['independent-handoff'])
32
+ required.push('handoff');
33
+ for (const role of required)
34
+ if (!bindings[role])
35
+ throw new ApiError(422, 'missing_profile_binding', 'A required role has no selected profile version.');
36
+ for (const [role, id] of Object.entries(bindings)) {
37
+ if (!roles.includes(role) || typeof id !== 'string' || !id)
38
+ throw new ApiError(422, 'invalid_profile_binding', 'A selected role binding is invalid.');
39
+ const version = versions.get(id) ?? this.#profile(id, role);
40
+ if (version.definition.role !== role)
41
+ throw new ApiError(422, 'profile_role_mismatch', 'The selected profile does not match its role.');
42
+ versions.set(id, version);
43
+ }
44
+ return jsonCopy(bindings);
45
+ });
46
+ return this.#validate(result, versions, signal);
47
+ }
48
+ async #validate(result, versions, signal) {
49
+ for (const version of versions.values()) {
50
+ this.store.coordinator.assertOutsideTransaction();
51
+ const report = await this.publication.profileReport({ definition: version.definition, resources: version.resources }, signal);
52
+ if (!report.valid)
53
+ throw new ApiError(422, 'invalid_profile', 'Selected profile configuration is invalid.', false, report.issues);
54
+ }
55
+ return result;
56
+ }
57
+ assemble(runId, definition, steps) {
58
+ this.store.coordinator.assertOutsideTransaction();
59
+ // The approved plan contract is positional: IDs identify executions, not
60
+ // workflow declarations, and both arrays retain workflow order.
61
+ if (steps.length !== definition.steps.length || steps.some(step => !step.id) || new Set(steps.map(step => step.id)).size !== steps.length)
62
+ throw new Error('instruction_plan_mismatch');
63
+ const snapshots = [];
64
+ for (const [index, step] of steps.entries())
65
+ for (const role of roles) {
66
+ const profile = step.profiles[role];
67
+ if (profile)
68
+ snapshots.push(this.assembleRole({ runId, stepExecutionId: step.id, role, profileVersionId: profile.profileVersionId,
69
+ stepInstructions: definition.steps[index].instructions ?? [], stepPackageResources: definition['instruction-resources'] ?? [],
70
+ ...(profile.snapshotId === undefined ? {} : { existingSnapshotId: profile.snapshotId }) }));
71
+ }
72
+ return snapshots;
73
+ }
74
+ assembleRole(input) {
75
+ this.store.coordinator.assertOutsideTransaction();
76
+ if (input.existingSnapshotId !== undefined)
77
+ return this.#original(input);
78
+ const version = this.#profile(input.profileVersionId, input.role);
79
+ const engine = this.options.engineInstructions[input.role];
80
+ if (typeof engine !== 'string')
81
+ throw new ApiError(422, 'invalid_instruction_source', 'Engine instruction content is unavailable.');
82
+ const profileFiles = this.#resources(version.resources), stepFiles = this.#resources(input.stepPackageResources);
83
+ const sections = [{ origin: 'engine', content: engine, contentDigest: sha256(engine) }];
84
+ for (const [origin, sources, resources] of [
85
+ ['profile', version.definition.instructions, profileFiles], ['step', input.stepInstructions, stepFiles],
86
+ ])
87
+ for (const source of sources) {
88
+ this.#source(source);
89
+ let content;
90
+ if (source.kind === 'inline')
91
+ content = source.text;
92
+ else if (source.location === 'package') {
93
+ const value = resources.get(source.path);
94
+ if (value === undefined)
95
+ throw new ApiError(422, 'invalid_instruction_source', 'Packaged instruction source is missing.');
96
+ content = value;
97
+ }
98
+ else
99
+ content = this.#workspace(input.runId, source.path);
100
+ sections.push({ origin, source: jsonCopy(source), content, contentDigest: sha256(content) });
101
+ }
102
+ const assembledText = sections.map(section => section.content).join('\n\n');
103
+ if (!assembledText)
104
+ throw new ApiError(422, 'invalid_instruction_source', 'Assembled instructions must not be empty.');
105
+ return { id: randomUUID(), runId: input.runId, stepExecutionId: input.stepExecutionId, role: input.role, profileVersionId: input.profileVersionId,
106
+ sections, assembledText, contentDigest: sha256(assembledText), createdAt: new Date((this.options.now ?? Date.now)()).toISOString() };
107
+ }
108
+ #profile(id, role) {
109
+ const version = this.store.find('profile_versions', id);
110
+ if (!version || version.id !== id)
111
+ throw new ApiError(422, 'profile_version_not_found', 'Selected immutable profile version is unavailable.');
112
+ if (!roles.includes(role) || version.definition.role !== role)
113
+ throw new ApiError(422, 'profile_role_mismatch', 'The selected profile does not match its role.');
114
+ return version;
115
+ }
116
+ #resources(resources) {
117
+ const files = new Map();
118
+ for (const resource of resources) {
119
+ if (!relativePath.test(resource.path) || typeof resource.content !== 'string')
120
+ throw new ApiError(422, 'invalid_instruction_source', 'Packaged instruction resource is invalid.');
121
+ if (files.has(resource.path))
122
+ throw new ApiError(422, 'duplicate_instruction_resource', 'Packaged instruction resource paths must be unique.');
123
+ files.set(resource.path, resource.content);
124
+ }
125
+ return files;
126
+ }
127
+ #source(source) {
128
+ if (!source || typeof source !== 'object' || Array.isArray(source))
129
+ throw new ApiError(422, 'invalid_instruction_source', 'Instruction source is invalid.');
130
+ if (source.kind === 'inline' && typeof source.text === 'string' && Object.keys(source).every(key => key === 'kind' || key === 'text'))
131
+ return;
132
+ if (source.kind === 'file' && (source.location === 'package' || source.location === 'workspace') &&
133
+ typeof source.path === 'string' && relativePath.test(source.path) &&
134
+ Object.keys(source).every(key => ['kind', 'location', 'path'].includes(key)))
135
+ return;
136
+ throw new ApiError(422, 'invalid_instruction_source', 'Instruction source must be explicit text or a normalized relative file path.');
137
+ }
138
+ #workspace(runId, path) {
139
+ this.store.coordinator.assertOutsideTransaction();
140
+ let bytes;
141
+ try {
142
+ bytes = this.options.readWorkspace(runId, path);
143
+ }
144
+ catch (error) {
145
+ if ((error instanceof ApiError && [400, 403, 404, 422].includes(error.status)) ||
146
+ (error instanceof Error && 'code' in error && typeof error.code === 'string' && sourceIoErrors.has(error.code)))
147
+ throw new ApiError(422, 'invalid_instruction_source', 'Workspace instruction source is unavailable.');
148
+ throw error;
149
+ }
150
+ if (!Buffer.isBuffer(bytes))
151
+ throw new TypeError('Instruction workspace reader must return a Buffer synchronously.');
152
+ try {
153
+ // ignoreBOM means do not consume the BOM: source bytes, CRLF, whitespace
154
+ // and empty content are preserved rather than normalized.
155
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
156
+ }
157
+ catch (error) {
158
+ if (error instanceof TypeError && 'code' in error && error.code === 'ERR_ENCODING_INVALID_ENCODED_DATA')
159
+ throw new ApiError(422, 'invalid_instruction_source', 'Workspace instruction source is not valid UTF-8.');
160
+ throw error;
161
+ }
162
+ }
163
+ #original(input) {
164
+ const invalid = () => new ApiError(422, 'invalid_instruction_snapshot', 'Pinned instruction snapshot is missing, mismatched or corrupt.');
165
+ let snapshot;
166
+ try {
167
+ snapshot = this.store.find('snapshots', input.existingSnapshotId);
168
+ }
169
+ catch (error) {
170
+ if (error instanceof SyntaxError)
171
+ throw invalid();
172
+ throw error;
173
+ }
174
+ if (!snapshot || snapshot.id !== input.existingSnapshotId || snapshot.runId !== input.runId || snapshot.stepExecutionId !== input.stepExecutionId ||
175
+ snapshot.role !== input.role || snapshot.profileVersionId !== input.profileVersionId || !roles.includes(snapshot.role) ||
176
+ !Array.isArray(snapshot.sections) || snapshot.sections[0]?.origin !== 'engine' ||
177
+ typeof snapshot.assembledText !== 'string' || !snapshot.assembledText || !Number.isFinite(Date.parse(snapshot.createdAt)))
178
+ throw invalid();
179
+ let previous = 0;
180
+ for (const section of snapshot.sections) {
181
+ if (!section || typeof section !== 'object')
182
+ throw invalid();
183
+ const order = ['engine', 'profile', 'step'].indexOf(section.origin);
184
+ if (order < previous || order < 0 || typeof section.content !== 'string' || section.contentDigest !== sha256(section.content))
185
+ throw invalid();
186
+ previous = order;
187
+ if (section.source !== undefined) {
188
+ try {
189
+ this.#source(section.source);
190
+ }
191
+ catch (error) {
192
+ if (error instanceof ApiError && error.status === 422)
193
+ throw invalid();
194
+ throw error;
195
+ }
196
+ if (section.source.kind === 'inline' && section.source.text !== section.content)
197
+ throw invalid();
198
+ }
199
+ }
200
+ if (snapshot.assembledText !== snapshot.sections.map(section => section.content).join('\n\n') ||
201
+ snapshot.contentDigest !== sha256(snapshot.assembledText))
202
+ throw invalid();
203
+ return snapshot;
204
+ }
205
+ }
@@ -0,0 +1,50 @@
1
+ import { EngineStore } from '../storage/store.js';
2
+ /** One durable episode, never nested retry loops. A fresh verifier does not
3
+ * create a new episode. Only starting an actual new operation gives a failure
4
+ * a new accounting identity; repeated observations cannot spend more credit. */
5
+ export class RetryLedger {
6
+ store;
7
+ constructor(store) {
8
+ this.store = store;
9
+ }
10
+ begin(episodeId, operationId) {
11
+ this.store.coordinator.atomic(() => {
12
+ const prior = this.store.private('execution_operation', operationId);
13
+ if (prior && prior.episodeId !== episodeId)
14
+ throw new Error('execution_operation_scope_conflict');
15
+ if (!prior)
16
+ this.store.setPrivate('execution_operation', operationId, { episodeId });
17
+ });
18
+ }
19
+ complete(operationId, submissionId) {
20
+ this.store.setPrivate('execution_completion', operationId, { submissionId });
21
+ }
22
+ failure(episodeId, operationId, input) {
23
+ return this.store.coordinator.atomic(() => {
24
+ const operation = this.store.private('execution_operation', operationId);
25
+ if (!operation || operation.episodeId !== episodeId)
26
+ throw new Error('execution_operation_not_started');
27
+ const prior = this.store.private('execution_failure', operationId);
28
+ if (!input.alreadyCharged && this.store.private('execution_completion', operationId))
29
+ return { category: input.category, retry: false, chargeAttempt: false };
30
+ if (prior)
31
+ return { ...prior, chargeAttempt: false };
32
+ const episode = this.store.private('retry_episode', episodeId) ?? { infrastructureUsed: 0, verificationUsed: 0 };
33
+ const outcome = { category: input.category, retry: false, chargeAttempt: false };
34
+ if (input.category === 'infrastructure' && episode.infrastructureUsed < input.infrastructureRetries) {
35
+ episode.infrastructureUsed++;
36
+ outcome.retry = true;
37
+ }
38
+ else {
39
+ outcome.chargeAttempt = !input.alreadyCharged;
40
+ if (input.verifier && episode.verificationUsed < input.verificationRetries) {
41
+ episode.verificationUsed++;
42
+ outcome.retry = true;
43
+ }
44
+ }
45
+ this.store.setPrivate('retry_episode', episodeId, episode);
46
+ this.store.setPrivate('execution_failure', operationId, outcome);
47
+ return outcome;
48
+ });
49
+ }
50
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import { ApiError } from '../server/errors.js';
2
+ export function durationMs(value) {
3
+ const match = /^([1-9][0-9]*)(ms|s|m|h|d)$/.exec(value);
4
+ const ms = match ? Number(match[1]) * ({ ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[match[2]] ?? NaN) : NaN;
5
+ if (!Number.isSafeInteger(ms) || ms < 1)
6
+ throw new ApiError(422, 'invalid_duration', 'Duration exceeds the supported elapsed-time range.');
7
+ return ms;
8
+ }
9
+ /** Long deadlines use chunks, never Node's overflowing timer coercion to 1ms. */
10
+ export function abortAt(deadlineAt, now = Date.now) {
11
+ const controller = new AbortController();
12
+ let timer;
13
+ const check = () => {
14
+ const remaining = deadlineAt - now();
15
+ if (remaining <= 0)
16
+ controller.abort();
17
+ else
18
+ timer = setTimeout(check, Math.min(remaining, 2_147_483_647));
19
+ };
20
+ check();
21
+ return { signal: controller.signal, close() { if (timer)
22
+ clearTimeout(timer); } };
23
+ }
@@ -0,0 +1,87 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { canonical, digest } from '../broker/policy.js';
3
+ /** Trusted journal projection, NOT an adapter command. The completion hook
4
+ * runs this inside the broker's own SQL root while effect work is still held.
5
+ * Unlike untrusted HTTP observations it may describe a historical fenced
6
+ * binding, but only with matching actual action/dispatch journal proof. */
7
+ export class ToolObservations {
8
+ store;
9
+ now;
10
+ constructor(store, now = Date.now) {
11
+ this.store = store;
12
+ this.now = now;
13
+ }
14
+ completed(input) {
15
+ return this.store.coordinator.atomic(() => {
16
+ const { binding, dispatch, result } = input;
17
+ const row = this.store.coordinator.db.prepare('SELECT state,body,result FROM broker_dispatches WHERE id=?').get(dispatch.id);
18
+ if (!row || row.state !== 'completed' || row.result !== canonical(result) || row.body !== canonical(dispatch))
19
+ throw new Error('unproven_tool_completion');
20
+ const action = this.action(binding, dispatch.actionRequestId);
21
+ if (action.state !== 'consumed' || dispatch.sessionId !== binding.sessionId || dispatch.epoch !== binding.epoch ||
22
+ dispatch.profileVersionId !== binding.profileVersionId || dispatch.actionDigest !== action.actionDigest || dispatch.resourceDigest !== action.resourceDigest)
23
+ throw new Error('tool_completion_scope_mismatch');
24
+ const key = digest([binding.sessionId, binding.epoch, action.clientActionId]);
25
+ return this.append(binding, key, { toolCallId: action.clientActionId, name: action.action.toolId, input: action.action.arguments,
26
+ status: result.success ? 'completed' : 'failed', output: result.text, actionRequestId: action.id, dispatchAuthorizationId: dispatch.id });
27
+ });
28
+ }
29
+ /** Denied/pre-dispatch failures and actual uncertain effects remain advisory.
30
+ * Replaying a completed invocation returns its already committed record. */
31
+ terminal(binding, invocationId, result) {
32
+ return this.store.coordinator.atomic(() => {
33
+ const key = digest([binding.sessionId, binding.epoch, invocationId]);
34
+ const prior = this.store.private('runtime_tool_observation', key);
35
+ if (prior)
36
+ return this.store.get('tool_history', prior.recordId);
37
+ const row = this.store.coordinator.db.prepare('SELECT body FROM broker_actions WHERE session_id=? AND epoch=? AND client_id=?')
38
+ .get(binding.sessionId, binding.epoch, invocationId);
39
+ const action = row ? this.action(binding, JSON.parse(row.body).id) : undefined;
40
+ const dispatch = action && this.store.coordinator.db.prepare('SELECT body,state,result FROM broker_dispatches WHERE action_id=?')
41
+ .get(action.id);
42
+ if (dispatch?.state === 'completed' && dispatch.result)
43
+ return this.completed({ binding, dispatch: JSON.parse(dispatch.body),
44
+ result: JSON.parse(dispatch.result) });
45
+ if (result.success)
46
+ throw new Error('successful_tool_observation_without_completion');
47
+ return this.append(binding, key, { toolCallId: invocationId, status: 'failed', output: result.text,
48
+ ...(action ? { name: action.action.toolId, input: action.action.arguments, actionRequestId: action.id } : {}),
49
+ ...(dispatch && ['started', 'uncertain'].includes(dispatch.state) ? { dispatchAuthorizationId: JSON.parse(dispatch.body).id } : {}) });
50
+ });
51
+ }
52
+ action(binding, id) {
53
+ const row = this.store.coordinator.db.prepare('SELECT body FROM broker_actions WHERE id=?').get(id);
54
+ if (!row)
55
+ throw new Error('tool_observation_action_missing');
56
+ const action = JSON.parse(row.body);
57
+ if (action.sessionId !== binding.sessionId || action.epoch !== binding.epoch || action.runId !== binding.runId ||
58
+ action.stepExecutionId !== binding.stepExecutionId || action.profileVersionId !== binding.profileVersionId)
59
+ throw new Error('tool_observation_scope_mismatch');
60
+ return action;
61
+ }
62
+ append(binding, key, event) {
63
+ const prior = this.store.private('runtime_tool_observation', key);
64
+ if (prior)
65
+ return this.store.get('tool_history', prior.recordId);
66
+ const session = this.store.get('sessions', binding.sessionId), run = this.store.get('runs', binding.runId);
67
+ if (session.runId !== binding.runId || session.stepExecutionId !== binding.stepExecutionId || !run.workspaceId)
68
+ throw new Error('tool_observation_assignment_missing');
69
+ const timestamp = new Date(this.now()).toISOString(), clientEventId = randomUUID();
70
+ const counter = this.store.private('tool_history_sequence', binding.runId);
71
+ const previous = counter?.value ?? this.store.coordinator.db.prepare("SELECT MAX(json_extract(body,'$.sequence')) AS value FROM engine_resources WHERE kind='tool_history' AND run_id=?")
72
+ .get(binding.runId).value ?? 0;
73
+ const sequence = previous + 1;
74
+ if (!Number.isSafeInteger(previous) || previous < 0 || !Number.isSafeInteger(sequence))
75
+ throw new Error('tool_history_sequence_exhausted');
76
+ const record = { id: randomUUID(), runId: binding.runId, sessionId: binding.sessionId, sequence,
77
+ event: { ...event, clientEventId, occurredAt: timestamp }, recordedAt: timestamp };
78
+ // Payloads originate in the trusted normalized action/result journal. No
79
+ // lossy text truncation or second asynchronous/model callback runs in SQL.
80
+ this.store.put('tool_history', record, { runId: binding.runId, parentId: binding.sessionId, immutable: true });
81
+ this.store.setPrivate('tool_history_sequence', binding.runId, { value: sequence });
82
+ this.store.setPrivate('runtime_tool_observation', key, { recordId: record.id });
83
+ this.store.setPrivate('tool_event_id', digest([binding.sessionId, binding.epoch, clientEventId]), { recordId: record.id });
84
+ this.store.event(binding.runId, 'tool_history_recorded', 'tool_history', record.id, { sessionId: binding.sessionId, sequence });
85
+ return record;
86
+ }
87
+ }