code60-transmission-server 0.1.0-staging.13 → 0.1.0-staging.16

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 (104) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +36 -345
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +60 -0
  5. package/dist/src/engine.js +481 -0
  6. package/dist/src/main.js +70 -25
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +184 -0
  9. package/package.json +16 -35
  10. package/reference/openapi.json +423 -0
  11. package/README.engine.md +0 -463
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -777
  14. package/dist/src/broker/native/README.md +0 -207
  15. package/dist/src/broker/native/build.js +0 -46
  16. package/dist/src/broker/native/command-helper.c +0 -93
  17. package/dist/src/broker/native/fs-helper.c +0 -529
  18. package/dist/src/broker/native/git-helper.c +0 -205
  19. package/dist/src/broker/policy.js +0 -149
  20. package/dist/src/broker/startup-lock.js +0 -14
  21. package/dist/src/broker/types.js +0 -11
  22. package/dist/src/cli/configure.js +0 -208
  23. package/dist/src/cli/daemon.js +0 -369
  24. package/dist/src/cli/helpers.js +0 -112
  25. package/dist/src/cli/main.js +0 -189
  26. package/dist/src/cli/runtime-build.js +0 -38
  27. package/dist/src/config/coding-policy.js +0 -4
  28. package/dist/src/config/deployment.js +0 -183
  29. package/dist/src/config/documents.js +0 -29
  30. package/dist/src/config/profile-validation.js +0 -129
  31. package/dist/src/config/schema-graph.js +0 -237
  32. package/dist/src/config/schema-loader.js +0 -185
  33. package/dist/src/config/validation-pool.js +0 -105
  34. package/dist/src/config/validation-protocol.js +0 -1
  35. package/dist/src/config/validation-worker.js +0 -106
  36. package/dist/src/config/workflow-language.js +0 -9
  37. package/dist/src/config/workflow-schema.json +0 -545
  38. package/dist/src/config/workflow-types.js +0 -1
  39. package/dist/src/config/workflow-validation.js +0 -95
  40. package/dist/src/engine/budgets.js +0 -50
  41. package/dist/src/engine/clocks.js +0 -27
  42. package/dist/src/engine/commands.js +0 -477
  43. package/dist/src/engine/contracts.js +0 -11
  44. package/dist/src/engine/drain-state.js +0 -31
  45. package/dist/src/engine/effective-permissions.js +0 -120
  46. package/dist/src/engine/instruction-pins.js +0 -205
  47. package/dist/src/engine/retries.js +0 -50
  48. package/dist/src/engine/state.js +0 -1
  49. package/dist/src/engine/timing.js +0 -23
  50. package/dist/src/engine/tool-observations.js +0 -87
  51. package/dist/src/engine/workflow-engine.js +0 -1864
  52. package/dist/src/mcp/catalog.js +0 -71
  53. package/dist/src/mcp/main.js +0 -26
  54. package/dist/src/mcp/server.js +0 -177
  55. package/dist/src/runtime/codex-app-server.js +0 -91
  56. package/dist/src/runtime/codex-executable.js +0 -50
  57. package/dist/src/runtime/containment.js +0 -82
  58. package/dist/src/runtime/engine-driver.js +0 -221
  59. package/dist/src/runtime/json-line-writer.js +0 -192
  60. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  61. package/dist/src/runtime/protocol-client.js +0 -264
  62. package/dist/src/runtime/protocol-pool.js +0 -183
  63. package/dist/src/runtime/protocol-projection.js +0 -393
  64. package/dist/src/runtime/protocol-types.js +0 -1
  65. package/dist/src/runtime/protocol-worker.js +0 -18
  66. package/dist/src/runtime/provider-bridge.js +0 -290
  67. package/dist/src/runtime/provider-credentials.js +0 -41
  68. package/dist/src/runtime/provider-transport.js +0 -406
  69. package/dist/src/runtime/runtime-broker.js +0 -213
  70. package/dist/src/runtime/workspace-instructions.js +0 -120
  71. package/dist/src/runtime/workspace-view.js +0 -74
  72. package/dist/src/server/api-contract.json +0 -11637
  73. package/dist/src/server/api-types.js +0 -1
  74. package/dist/src/server/application.js +0 -44
  75. package/dist/src/server/auth.js +0 -67
  76. package/dist/src/server/broker-handlers.js +0 -242
  77. package/dist/src/server/coding.js +0 -281
  78. package/dist/src/server/control-plane.js +0 -50
  79. package/dist/src/server/deployment.js +0 -249
  80. package/dist/src/server/errors.js +0 -22
  81. package/dist/src/server/history-handlers.js +0 -130
  82. package/dist/src/server/http.js +0 -124
  83. package/dist/src/server/paging.js +0 -56
  84. package/dist/src/server/publication.js +0 -119
  85. package/dist/src/server/tool-event-handler.js +0 -77
  86. package/dist/src/server/workspace-handlers.js +0 -34
  87. package/dist/src/storage/coordinator.js +0 -224
  88. package/dist/src/storage/startup-lock.js +0 -71
  89. package/dist/src/storage/store.js +0 -167
  90. package/dist/src/tools/check-worker.js +0 -81
  91. package/dist/src/tools/checks.js +0 -117
  92. package/dist/src/tools/command-check.js +0 -34
  93. package/dist/src/tools/commands.js +0 -312
  94. package/dist/src/tools/developer.js +0 -355
  95. package/dist/src/tools/dns.js +0 -248
  96. package/dist/src/tools/http-contract.js +0 -38
  97. package/dist/src/tools/http.js +0 -358
  98. package/dist/src/tools/index.js +0 -194
  99. package/dist/src/tools/worker-check.js +0 -73
  100. package/dist/src/workspaces/git.js +0 -227
  101. package/dist/src/workspaces/index.js +0 -937
  102. package/dist/src/workspaces/source.js +0 -295
  103. package/examples/deployment.local.json +0 -22
  104. package/scripts/postinstall.mjs +0 -26
@@ -1,120 +0,0 @@
1
- import { normalizeHost, validatePolicy } from '../broker/policy.js';
2
- import { ApiError } from '../server/errors.js';
3
- const operations = ['read', 'write', 'delete'];
4
- function stronger(a, b) {
5
- return a === 'deny' || b === 'deny' ? 'deny' : a === 'require_approval' || b === 'require_approval' ? 'require_approval' : 'allow';
6
- }
7
- function resourceKey(rule) {
8
- return rule.kind === 'filesystem'
9
- ? JSON.stringify([rule.kind, rule.root, rule.rootId, rule.path, rule.recursive, rule.effect])
10
- : JSON.stringify([rule.kind, rule.protocol, rule.port, rule.host, rule.effect]);
11
- }
12
- function add(target, rule) {
13
- const key = resourceKey(rule), prior = target.get(key);
14
- if (rule.kind === 'filesystem') {
15
- const selected = new Set([...rule.operations, ...(prior?.kind === 'filesystem' ? prior.operations : [])]);
16
- target.set(key, { kind: 'filesystem', root: rule.root, ...(rule.rootId === undefined ? {} : { rootId: rule.rootId }),
17
- path: rule.path, recursive: rule.recursive, operations: operations.filter(operation => selected.has(operation)), effect: rule.effect });
18
- }
19
- else
20
- target.set(key, { kind: 'network', protocol: rule.protocol, port: rule.port,
21
- host: rule.host === '*' ? '*' : normalizeHost(rule.host), effect: rule.effect });
22
- }
23
- function normalized(policy) {
24
- validatePolicy(policy);
25
- const tools = new Map(), resources = new Map();
26
- for (const rule of policy.rules) {
27
- if (rule.kind === 'tool') {
28
- const prior = tools.get(rule.toolId);
29
- tools.set(rule.toolId, prior === undefined ? rule.effect : stronger(prior, rule.effect));
30
- }
31
- else
32
- add(resources, rule.kind === 'network' && rule.host !== '*' ? { ...rule, host: normalizeHost(rule.host) } : rule);
33
- }
34
- return { tools, resources: [...resources.values()] };
35
- }
36
- function toolEffect(tools, id) {
37
- const wildcard = tools.get('*'), exact = tools.get(id);
38
- return wildcard === undefined ? exact ?? 'deny' : exact === undefined ? wildcard : stronger(wildcard, exact);
39
- }
40
- function scopeKey(rule) {
41
- return rule.kind === 'filesystem' ? JSON.stringify([rule.kind, rule.root, rule.rootId])
42
- : JSON.stringify([rule.kind, rule.protocol, rule.port]);
43
- }
44
- function positives(rules) {
45
- const groups = new Map();
46
- for (const rule of rules)
47
- if (rule.effect !== 'deny') {
48
- const key = scopeKey(rule), group = groups.get(key);
49
- if (group)
50
- group.push(rule);
51
- else
52
- groups.set(key, [rule]);
53
- }
54
- return groups;
55
- }
56
- function intersection(a, b) {
57
- const effect = stronger(a.effect, b.effect);
58
- if (a.kind === 'network' && b.kind === 'network') {
59
- if (a.host !== '*' && b.host !== '*' && a.host !== b.host)
60
- return undefined;
61
- return { ...a, host: a.host === '*' ? b.host : a.host, effect };
62
- }
63
- if (a.kind !== 'filesystem' || b.kind !== 'filesystem')
64
- return undefined;
65
- const shared = operations.filter(operation => a.operations.includes(operation) && b.operations.includes(operation));
66
- if (!shared.length)
67
- return undefined;
68
- let path, recursive;
69
- if (a.path === b.path) {
70
- path = a.path;
71
- recursive = a.recursive && b.recursive;
72
- }
73
- else if (a.recursive && (a.path === '.' || b.path.startsWith(`${a.path}/`))) {
74
- path = b.path;
75
- recursive = b.recursive;
76
- }
77
- else if (b.recursive && (b.path === '.' || a.path.startsWith(`${b.path}/`))) {
78
- path = a.path;
79
- recursive = a.recursive;
80
- }
81
- else
82
- return undefined;
83
- return { kind: 'filesystem', root: a.root, ...(a.rootId === undefined ? {} : { rootId: a.rootId }),
84
- path, recursive, operations: shared, effect };
85
- }
86
- /** Exact pointwise intersection, then the broker's all-resources conjunction.
87
- * Positive supports intersect; explicit denial exceptions from EITHER side
88
- * survive. Approval dominates allowance on every overlapping positive scope. */
89
- export function effectivePermissions(profile, deployment, role, configuredTools) {
90
- if (configuredTools.some(id => typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)))
91
- throw new ApiError(422, 'invalid_configured_tool', 'Configured tools must be concrete validated profile tool IDs.');
92
- const left = normalized(profile), right = normalized(deployment);
93
- const rules = [], resources = new Map();
94
- for (const id of [...new Set(configuredTools)].sort()) {
95
- const effect = stronger(toolEffect(left.tools, id), toolEffect(right.tools, id));
96
- if (effect !== 'deny')
97
- rules.push({ kind: 'tool', toolId: id, effect });
98
- }
99
- for (const rule of [...left.resources, ...right.resources])
100
- if (rule.effect === 'deny')
101
- add(resources, rule);
102
- const rightGroups = positives(right.resources);
103
- for (const [key, group] of positives(left.resources)) {
104
- const others = rightGroups.get(key);
105
- if (!others)
106
- continue;
107
- for (const a of group)
108
- for (const b of others) {
109
- const shared = intersection(a, b);
110
- if (shared)
111
- add(resources, shared);
112
- }
113
- }
114
- if (role === 'verifier')
115
- add(resources, { kind: 'filesystem', root: 'workspace', path: '.', recursive: true,
116
- operations: ['write', 'delete'], effect: 'deny' });
117
- rules.push(...resources.values());
118
- rules.sort((a, b) => { const x = JSON.stringify(a), y = JSON.stringify(b); return x < y ? -1 : x > y ? 1 : 0; });
119
- return { defaultEffect: 'deny', rules };
120
- }
@@ -1,205 +0,0 @@
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
- }
@@ -1,50 +0,0 @@
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
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,23 +0,0 @@
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
- }
@@ -1,87 +0,0 @@
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
- }