code60-transmission-server 0.1.0-staging.3 → 0.1.0-staging.6

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 (36) hide show
  1. package/README.engine.md +64 -2
  2. package/README.md +66 -5
  3. package/dist/src/broker/native/README.md +15 -0
  4. package/dist/src/broker/native/build.js +3 -0
  5. package/dist/src/broker/native/command-helper.c +93 -0
  6. package/dist/src/cli/configure.js +193 -0
  7. package/dist/src/cli/daemon.js +5 -1
  8. package/dist/src/cli/helpers.js +12 -4
  9. package/dist/src/cli/main.js +12 -3
  10. package/dist/src/cli/runtime-build.js +38 -0
  11. package/dist/src/config/coding-policy.js +4 -0
  12. package/dist/src/config/deployment.js +26 -10
  13. package/dist/src/config/workflow-schema.json +11 -0
  14. package/dist/src/engine/commands.js +35 -4
  15. package/dist/src/engine/workflow-engine.js +70 -15
  16. package/dist/src/main.js +4 -1
  17. package/dist/src/mcp/main.js +4 -2
  18. package/dist/src/mcp/server.js +37 -6
  19. package/dist/src/runtime/engine-driver.js +11 -2
  20. package/dist/src/runtime/provider-bridge.js +4 -2
  21. package/dist/src/runtime/provider-transport.js +7 -5
  22. package/dist/src/server/api-contract.json +530 -2
  23. package/dist/src/server/application.js +9 -3
  24. package/dist/src/server/coding.js +254 -0
  25. package/dist/src/server/deployment.js +18 -6
  26. package/dist/src/server/history-handlers.js +16 -2
  27. package/dist/src/server/workspace-handlers.js +1 -1
  28. package/dist/src/tools/checks.js +12 -1
  29. package/dist/src/tools/command-check.js +34 -0
  30. package/dist/src/tools/commands.js +310 -0
  31. package/dist/src/tools/developer.js +351 -0
  32. package/dist/src/tools/index.js +19 -2
  33. package/dist/src/workspaces/index.js +244 -22
  34. package/dist/src/workspaces/source.js +295 -0
  35. package/package.json +4 -2
  36. package/scripts/postinstall.mjs +2 -1
@@ -0,0 +1,38 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { packageRoot, packageVersion } from './helpers.js';
5
+ /** Compare installed engine code, including native containment sources, rather
6
+ * than just semver: a staging build and a checkout can share a version. */
7
+ export function runtimeBuildId() {
8
+ const hash = createHash('sha256'), packaged = packageRoot(), root = existsSync(join(packaged, 'dist', 'src')) ? join(packaged, 'dist', 'src') : join(packaged, 'src');
9
+ const visit = (directory) => {
10
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
11
+ const path = join(directory, entry.name);
12
+ if (entry.isDirectory() && entry.name !== '.build')
13
+ visit(path);
14
+ else if (entry.isFile() && /\.(js|json|c)$/.test(entry.name)) {
15
+ hash.update(relative(root, path));
16
+ hash.update('\0');
17
+ hash.update(readFileSync(path));
18
+ hash.update('\0');
19
+ }
20
+ }
21
+ };
22
+ visit(root);
23
+ hash.update(packageVersion());
24
+ return hash.digest('hex');
25
+ }
26
+ export function recordRuntimeBuild(stateDirectory) {
27
+ // Called only after acquiring the exclusive startup lock, before listening.
28
+ writeFileSync(join(stateDirectory, 'engine-runtime.json'), JSON.stringify({ pid: process.pid, version: packageVersion(), buildId: runtimeBuildId() }), { mode: 0o600 });
29
+ }
30
+ export function assertRuntimeBuild(stateDirectory, pid) {
31
+ try {
32
+ const current = JSON.parse(readFileSync(join(stateDirectory, 'engine-runtime.json'), 'utf8'));
33
+ if (current.pid === pid && current.buildId === runtimeBuildId())
34
+ return;
35
+ }
36
+ catch { /* Older engines have no build record. */ }
37
+ throw new Error(`Engine upgrade required for ${stateDirectory} (PID ${pid}). Stop it with code60 stop --state-directory ${JSON.stringify(stateDirectory)}, then reconnect using this installation. Existing runs and configuration are preserved; an upgrade never silently replaces an active engine.`);
38
+ }
@@ -0,0 +1,4 @@
1
+ import { evaluatePolicy } from '../broker/policy.js';
2
+ export function missingCodingPermissions(policy) {
3
+ return ['read_file', 'write_file', 'run_command'].filter(toolId => evaluatePolicy(policy, toolId, [{ kind: 'filesystem', root: 'workspace', path: '.', operation: toolId === 'read_file' ? 'read' : 'write', identityDigest: 'sha256:' + '0'.repeat(64) }]) === 'deny');
4
+ }
@@ -1,6 +1,7 @@
1
+ import { accessSync, lstatSync, realpathSync } from 'node:fs';
1
2
  import { isAbsolute } from 'node:path';
2
3
  import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
3
- import { normalizeHost, validatePolicy } from '../broker/policy.js';
4
+ import { normalizeHost, relativePath, validatePolicy } from '../broker/policy.js';
4
5
  import { HTTP_DEPLOYMENT_SCHEMA } from '../tools/http-contract.js';
5
6
  import contract from '../server/api-contract.json' with { type: 'json' };
6
7
  import { ApiError } from '../server/errors.js';
@@ -26,14 +27,17 @@ const schema = { $id: 'urn:code60:deployment', ...object({
26
27
  deploymentPolicy: permission, agentHttp: HTTP_DEPLOYMENT_SCHEMA,
27
28
  schemaHttp: object({ ...http.properties, timeoutMs: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
28
29
  networkPolicy: permission }, ['networkPolicy']),
29
- checks: { type: 'array', maxItems: 64, items: object({
30
- id: text, description: { type: 'string', minLength: 1, maxLength: 4096 }, version: text,
31
- predicate: { oneOf: [
32
- object({ kind: { const: 'text_includes' }, needle: { type: 'string', minLength: 1, maxLength: 4096 } }),
33
- object({ kind: { const: 'json_pointer_equals' }, pointer: { type: 'string', maxLength: 4096 }, expected: {} }),
34
- object({ kind: { const: 'json_schema' }, schema: { type: ['object', 'boolean'] } }),
35
- ] },
36
- }) },
30
+ commands: object({ enabled: { type: 'boolean' }, network: { enum: ['outbound', 'none'] }, toolchainPaths: { type: 'array', items: { type: 'string' } }, generatedPaths: { type: 'array', items: { type: 'string' } }, timeoutMs: { type: 'integer', minimum: 1, maximum: 86400000 }, maxOutputBytes: { type: 'integer', minimum: 65536, maximum: 1073741824 } }, []),
31
+ sourceQuotas: object({ entries: { type: 'integer', minimum: 1 }, fileBytes: { type: 'integer', minimum: 1 }, totalBytes: { type: 'integer', minimum: 1 } }, []),
32
+ contextBytes: { type: 'integer', minimum: 16384, maximum: 1048576 },
33
+ checks: { type: 'array', maxItems: 64, items: { oneOf: [object({
34
+ id: text, description: { type: 'string', minLength: 1, maxLength: 4096 }, version: text,
35
+ predicate: { oneOf: [
36
+ object({ kind: { const: 'text_includes' }, needle: { type: 'string', minLength: 1, maxLength: 4096 } }),
37
+ object({ kind: { const: 'json_pointer_equals' }, pointer: { type: 'string', maxLength: 4096 }, expected: {} }),
38
+ object({ kind: { const: 'json_schema' }, schema: { type: ['object', 'boolean'] } }),
39
+ ] },
40
+ }), { $ref: 'urn:code60:api#/components/schemas/CommandCheck' }] } },
37
41
  deploymentRoots: { type: 'array', maxItems: 8, items: object({ id: text, path: { type: 'string', minLength: 1, maxLength: 4096 } }) },
38
42
  providers: { type: 'array', maxItems: 16, items: object({
39
43
  id: text, endpoint: { type: 'string', minLength: 1, maxLength: 4096 }, networkPolicy: permission,
@@ -99,6 +103,12 @@ export async function loadDeploymentConfiguration(path, validation) {
99
103
  const config = decoded.value;
100
104
  validatePolicy(config.deploymentPolicy);
101
105
  validatePolicy(config.schemaHttp.networkPolicy);
106
+ for (const path of config.commands?.generatedPaths ?? [])
107
+ if (relativePath(path) === '.')
108
+ throw new ApiError(422, 'invalid_generated_path', 'Generated paths must be explicit relative child paths.');
109
+ for (const path of config.commands?.toolchainPaths ?? [])
110
+ if (!isAbsolute(path))
111
+ throw new ApiError(422, 'invalid_toolchain_path', 'Toolchain paths must be absolute.');
102
112
  if (!isAbsolute(config.runtime.executable) || /[\0\r\n]/.test(config.runtime.executable) ||
103
113
  new Set(config.runtime.models.map(model => model.id)).size !== config.runtime.models.length ||
104
114
  new Set(config.checks.map(check => check.id)).size !== config.checks.length ||
@@ -141,6 +151,12 @@ export async function loadDeploymentConfiguration(path, validation) {
141
151
  return config;
142
152
  }
143
153
  export function runtimeAdvertisement(config, tools) {
154
+ let available = false;
155
+ try {
156
+ accessSync(config.runtime.executable, constants.X_OK);
157
+ available = config.runtime.enabled && lstatSync(realpathSync(config.runtime.executable)).isFile();
158
+ }
159
+ catch { /* Readiness reports the actionable executable error. */ }
144
160
  const toolConfigurations = tools.toolConfigurations().map(tool => {
145
161
  const configurationSchema = tool.configurationSchema;
146
162
  if (typeof configurationSchema !== 'boolean' && (!configurationSchema || typeof configurationSchema !== 'object' || Array.isArray(configurationSchema)))
@@ -149,7 +165,7 @@ export function runtimeAdvertisement(config, tools) {
149
165
  });
150
166
  return {
151
167
  runtime: { id: LOCAL_RUNTIME_ID, name: 'Contained local Codex app-server', protocol: 'acp',
152
- available: config.runtime.enabled, authenticationState: config.runtime.enabled ? 'ready' : 'requires_configuration' },
168
+ available, authenticationState: available ? 'ready' : 'requires_configuration' },
153
169
  configuration: { runtimeId: LOCAL_RUNTIME_ID,
154
170
  providers: [{ id: LOCAL_PROVIDER_ID, models: structuredClone(config.runtime.models) },
155
171
  ...(config.providers ?? []).map(provider => ({ id: provider.id,
@@ -91,6 +91,17 @@
91
91
  "items": {
92
92
  "$ref": "#/$defs/InstructionResource"
93
93
  }
94
+ },
95
+ "inputs": {
96
+ "description": "Optional JSON Schema for immutable run inputs",
97
+ "oneOf": [
98
+ {
99
+ "type": "object"
100
+ },
101
+ {
102
+ "type": "boolean"
103
+ }
104
+ ]
94
105
  }
95
106
  },
96
107
  "required": [
@@ -156,6 +156,11 @@ export class RunCommands {
156
156
  if (!validated.report.valid || !validated.definition)
157
157
  throw new ApiError(422, 'invalid_workflow', 'Workflow configuration is invalid.', false, validated.report.issues);
158
158
  const definition = validated.definition, bindings = await this.options.pins.resolve(definition, input.agentProfiles ?? {}, context.signal);
159
+ if (definition.inputs !== undefined) {
160
+ const report = await this.options.publication.validation.run({ kind: 'artifact', rootUri: 'urn:code60:run-inputs', resources: [{ uri: 'urn:code60:run-inputs', schema: definition.inputs }], value: input.inputs ?? null }, { signal: context.signal });
161
+ if (!report.valid)
162
+ throw new ApiError(422, 'invalid_run_inputs', 'Run inputs do not match the workflow input schema.', false, report.errors);
163
+ }
159
164
  // Do not charge a new run, open a native root or reserve a lease on replay.
160
165
  const raced = this.store.receipt(identity);
161
166
  if (raced)
@@ -171,9 +176,10 @@ export class RunCommands {
171
176
  pauseGracePeriod: config?.['pause-grace-period'] ?? '30s', approvalTimeout: config?.['approval-timeout'] ?? '24h', ...input.policy };
172
177
  const approvalTimeoutMs = durationMs(policy.approvalTimeout);
173
178
  const plan = { definition, ordinal: 0, stage: 'startup', timingPolicy, clock: runClock, stepClocks: {}, queuedDecisions: [],
179
+ resultMode: input.resultMode ?? 'commit', inputs: input.inputs ?? null, inputArtifacts: input.inputArtifacts ?? [],
174
180
  steps: definition.steps.map((_step, index) => ({ id: randomUUID(), profiles: Object.fromEntries(Object.entries(bindings[index]).map(([role, profileVersionId]) => [role, { profileVersionId }])),
175
181
  verificationCharges: 0, verificationConsumedMs: 0 })) };
176
- const run = { id, workflowVersionId: version.id, workspaceId: input.workspaceId, state: 'starting', version: 1, policy,
182
+ const run = { id, resultMode: input.resultMode ?? 'commit', workflowVersionId: version.id, workspaceId: input.workspaceId, state: 'starting', version: 1, policy,
177
183
  timing: status(runClock, false, now), createdAt, updatedAt: createdAt,
178
184
  executionControl: { status: 'running', inFlightWork: [] }, pendingBlockIds: [], approvalWait: { status: 'none', pendingApprovalIds: [], inFlightWork: [] },
179
185
  agentProfiles: { ...config?.['agent-profiles'], ...input.agentProfiles } };
@@ -181,6 +187,12 @@ export class RunCommands {
181
187
  this.options.workspaces.acquireLease(input.workspaceId, id, { onAdmittedSql: () => {
182
188
  this.store.put('runs', run);
183
189
  this.savePlan(id, plan);
190
+ for (const document of input.inputArtifacts ?? []) {
191
+ const artifactId = randomUUID();
192
+ this.store.put('artifacts', { id: artifactId, runId: id, kind: 'input', document, contentDigest: digest(document.content), state: 'accepted', createdAt }, { runId: id, immutable: true });
193
+ }
194
+ plan.inputArtifacts = [];
195
+ this.savePlan(id, plan);
184
196
  this.store.coordinator.db.prepare('INSERT INTO broker_runs VALUES (?,?)').run(id, canonical({ operatorPaused: false, cancelled: false, holds: [], deadlineAt: runClock.deadlineAt ?? null, approvalTimeoutMs }));
185
197
  for (const [index, stepPlan] of plan.steps.entries()) {
186
198
  const step = definition.steps[index];
@@ -192,7 +204,7 @@ export class RunCommands {
192
204
  receipt = { status: 202, headers: { Location: `/api/v1/runs/${id}`, ETag: this.store.etag('runs', id) }, body: run };
193
205
  this.store.saveReceipt(identity, receipt);
194
206
  this.wake(id);
195
- } });
207
+ } }, input.resultMode ?? 'commit');
196
208
  return { receipt, replay: false };
197
209
  }
198
210
  pause(context) {
@@ -240,14 +252,33 @@ export class RunCommands {
240
252
  }
241
253
  for (const { value } of this.store.list('sessions', { runId: run.id, limit: Number.MAX_SAFE_INTEGER }))
242
254
  this.options.auth.revokeSession(value.id);
243
- this.updateRun(run.id, { state: 'pausing', executionControl: { status: 'pausing', inFlightWork: this.options.work(run.id) } });
255
+ const now = this.now();
256
+ this.updateRun(run.id, { state: 'pausing', executionControl: { status: 'pausing',
257
+ continuationState: run.executionControl.continuationState ?? (['pausing', 'paused', 'resuming'].includes(run.state) ? 'interrupted' : run.state),
258
+ pauseOperationId: operation.id, requestedAt: new Date(now).toISOString(),
259
+ graceDeadlineAt: new Date(now + durationMs(run.policy.pauseGracePeriod ?? '30s')).toISOString(), inFlightWork: this.options.work(run.id) } });
244
260
  return this.operationReceipt(operation);
245
261
  });
246
262
  }
247
263
  recover(context) {
248
264
  return this.runCommand(context, 'recoveries', (run, plan) => {
249
265
  const recovery = run.pendingBlockIds.map(id => this.store.get('blocks', id)).filter(block => block.reason === 'resume_requires_recovery' && block.recoveryAllowed);
250
- if (run.state !== 'interrupted' && !recovery.length && run.executionControl.continuationState !== 'interrupted')
266
+ const commandRecovery = this.options.commandRecoveryRequired?.(run.id) ?? false;
267
+ const resolution = context.body.commandResolution;
268
+ if (commandRecovery && !resolution)
269
+ throw new ApiError(422, 'command_resolution_required', 'Read get_coding_task_result and supply commandResolution with the observed sourceDigest and preserve_changes or rollback.');
270
+ if (resolution && commandRecovery)
271
+ this.store.setPrivate('command_resolution', run.id, resolution);
272
+ if (plan.recoveryOperationId && commandRecovery && resolution) {
273
+ const held = this.store.private('command_recovery_block', run.id);
274
+ if (held)
275
+ this.resolveBlock(held.id);
276
+ const operation = this.store.get('operations', plan.recoveryOperationId);
277
+ this.store.put('operations', { ...operation, state: 'running' }, { runId: run.id });
278
+ this.wake(run.id);
279
+ return this.operationReceipt(operation);
280
+ }
281
+ if (run.state !== 'interrupted' && !recovery.length && run.executionControl.continuationState !== 'interrupted' && !commandRecovery)
251
282
  conflict();
252
283
  if (plan.recoveryOperationId)
253
284
  conflict('Recovery is already pending.');
@@ -72,6 +72,8 @@ export class WorkflowEngine {
72
72
  for (const job of this.options.workspaces.activeWork(runId))
73
73
  if (!(this.#readProof.has(runId) && job.state === 'uncertain'))
74
74
  work.push({ id: job.id, kind: 'engine_transition', description: job.state === 'uncertain' ? 'Workspace effect requires read-only reconciliation' : 'Workspace Git effect' });
75
+ if (this.options.additionalWork?.(runId))
76
+ work.push({ id: 'command_processes', kind: 'engine_transition', description: 'Command processes or unresolved command settlement' });
75
77
  return work;
76
78
  }
77
79
  quiet(runId) { return this.work(runId).length === 0; }
@@ -157,6 +159,8 @@ export class WorkflowEngine {
157
159
  this.commands.options.auth.revokeSession(session.id);
158
160
  }
159
161
  });
162
+ if (this.options.closeCommands)
163
+ await this.options.closeCommands();
160
164
  for (const { id } of ids)
161
165
  await this.stopSessions(id);
162
166
  await Promise.allSettled([...this.#actors.values()]);
@@ -574,18 +578,54 @@ export class WorkflowEngine {
574
578
  const plan = this.commands.plan(session.runId), step = plan.definition.steps[plan.ordinal];
575
579
  const byteCount = this.store.coordinator.db.prepare("SELECT COALESCE(SUM(length(CAST(body AS BLOB))),0) AS n FROM engine_resources WHERE kind='artifacts' AND id IN (SELECT value FROM json_each(?))")
576
580
  .get(JSON.stringify(authority.inputArtifactIds));
577
- if (byteCount.n > (this.options.maxContextBytes ?? 67_108_864))
581
+ if (!authority.binding.configuredTools.includes('get_context') && byteCount.n > (this.options.maxContextBytes ?? 67_108_864))
578
582
  throw new ApiError(422, 'assignment_context_limit', 'Assigned artifact context exceeds the configured runtime bound.');
579
583
  const artifacts = authority.inputArtifactIds.map(id => this.store.get('artifacts', id));
584
+ const bounded = authority.binding.configuredTools.includes('get_context'), limit = this.options.contextBytes ?? 65_536;
585
+ const selected = [];
586
+ let bytes = 0;
587
+ for (const artifact of [...artifacts].reverse()) {
588
+ const size = Buffer.byteLength(JSON.stringify(artifact));
589
+ if (!bounded || bytes + size < limit / 2) {
590
+ selected.unshift(artifact);
591
+ bytes += size;
592
+ }
593
+ }
594
+ const historyAccess = this.store.private('session_access', sessionId);
595
+ const history = this.store.list('tool_history', { runId: session.runId, ...(historyAccess ? { after: historyAccess.historyAfterSeq, through: historyAccess.historyThroughSeq } : {}), limit: Number.MAX_SAFE_INTEGER }).slice(-20).map(({ value }) => ({ id: value.id, name: value.event.name, status: value.event.status, output: JSON.stringify(value.event.output ?? '').slice(0, 1024) }));
596
+ const messages = this.store.coordinator.db.prepare("SELECT id,body FROM engine_private WHERE scope='task_message' AND json_extract(body,'$.runId')=? AND (json_extract(body,'$.delivered')=0 OR ?=1) ORDER BY rowid").all(session.runId, session.submissionsUsed === 0 ? 1 : 0).map(row => {
597
+ const message = JSON.parse(row.body);
598
+ this.store.setPrivate('task_message', row.id, { ...message, delivered: true });
599
+ return { id: row.id, text: message.text };
600
+ });
580
601
  const ids = criterionIds(step.exitCriteria.semantic?.criteria ?? []);
581
602
  const format = session.effectiveConfiguration.definition.runtime.options?.artifactFormat === 'yaml' ? 'YAML' : 'JSON';
582
- return `Perform only the current assigned ${authority.phase} task. Use only the broker tools. Return ONLY the ${format} output document, without Markdown fences. Do not submit HTTP envelopes or claim Git authority.\n` +
583
- (authority.phase === 'verification' ? 'Check every assigned criterion against the exact artifact and pinned live workspace revision. approve requires ALL pass. revise requires actionable guidance. Project edits are forbidden.\n' : '') +
584
- JSON.stringify({ workflowStepId: step.id, name: step.name ?? step.id, outputSchema: authority.outputSchema, phase: authority.phase,
585
- criteria: (step.exitCriteria.semantic?.criteria ?? []).map((description, index) => ({ criterionId: ids[index], description })),
586
- ...(authority.subjectSubmissionId ? { subjectSubmissionId: authority.subjectSubmissionId, workspaceRevisionId: authority.workspaceRevisionId } : {}),
587
- artifacts: artifacts.map(value => ({ id: value.id, kind: value.kind, document: value.document, contentDigest: value.contentDigest })),
588
- schemaResources: plan.graph.resources });
603
+ const prefix = `Perform only the current assigned ${authority.phase} task. Use only the broker tools. Return ONLY the ${format} output document, without Markdown fences. Do not submit HTTP envelopes or claim Git authority.\n` +
604
+ (authority.phase === 'verification' ? 'Check every assigned criterion against the exact artifact and pinned live workspace revision. approve requires ALL pass. revise requires actionable guidance. Project edits are forbidden.\n' : '') + (bounded ? 'Use get_context to retrieve omitted inputs, schemas, artifacts, or user guidance before completing the task.\n' : '');
605
+ const payload = { workflowStepId: step.id, name: step.name ?? step.id, outputSchema: authority.outputSchema, phase: authority.phase,
606
+ criteria: (step.exitCriteria.semantic?.criteria ?? []).map((description, index) => ({ criterionId: ids[index], description })),
607
+ ...(authority.subjectSubmissionId ? { subjectSubmissionId: authority.subjectSubmissionId, workspaceRevisionId: authority.workspaceRevisionId } : {}),
608
+ inputs: bounded && Buffer.byteLength(JSON.stringify(plan.inputs ?? null)) > limit / 4 ? { retrieve: 'get_context', kind: 'inputs' } : plan.inputs ?? null, inputArtifacts: plan.inputArtifacts ?? [], userMessages: bounded ? messages.slice(-8).map(m => ({ id: m.id, text: m.text.slice(0, 2048), ...(m.text.length > 2048 ? { retrieve: 'get_context', kind: 'messages', truncated: true } : {}) })) : messages,
609
+ capabilities: { tools: authority.binding.configuredTools, permissions: session.effectiveConfiguration.effectivePermissions, limits: session.limits, submissionsUsed: session.submissionsUsed, remainingSubmissions: session.limits.maxSubmissions === undefined ? null : Math.max(0, session.limits.maxSubmissions - session.submissionsUsed), timing: session.timing, commands: this.options.commandCapabilities?.() ?? null },
610
+ recentToolHistory: history, artifactManifest: artifacts.slice(-100).map(a => ({ id: a.id, kind: a.kind, bytes: Buffer.byteLength(a.document.content) })),
611
+ artifacts: selected.map(value => ({ id: value.id, kind: value.kind, document: value.document, contentDigest: value.contentDigest })),
612
+ schemaResources: bounded ? plan.graph.resources.filter(r => JSON.stringify(r.schema).length < 8192).slice(0, 4) : plan.graph.resources };
613
+ if (bounded) {
614
+ const payloadLimit = limit - Buffer.byteLength(prefix);
615
+ payload.guidanceManifest = (plan.workspaceInstructions?.files ?? []).filter(file => file.selected).slice(0, 32).map(file => ({ path: file.path, bytes: Buffer.byteLength(file.content), sha256: file.sha256 }));
616
+ payload.questions = this.store.coordinator.db.prepare("SELECT body FROM engine_private WHERE scope='worker_question' AND json_extract(body,'$.runId')=? ORDER BY rowid DESC LIMIT 8").all(session.runId).map(row => { const q = JSON.parse(row.body); return { id: q.id, state: q.state, question: q.question.slice(0, 2048), answer: q.answer?.slice(0, 2048), retrieve: 'get_context', kind: 'questions' }; });
617
+ payload.contextRetrieval = { tool: 'get_context', artifacts: 'artifacts', priorHistory: 'history', schemas: 'schemas', messages: 'messages', questions: 'questions', guidance: 'guidance' };
618
+ if (Buffer.byteLength(JSON.stringify(payload.outputSchema)) > limit / 4)
619
+ payload.outputSchema = { retrieve: 'get_context', kind: 'schema' };
620
+ for (const key of ['schemaResources', 'recentToolHistory', 'artifacts', 'artifactManifest', 'userMessages', 'questions', 'guidanceManifest']) {
621
+ const items = payload[key];
622
+ while (items.length && Buffer.byteLength(JSON.stringify(payload)) > payloadLimit)
623
+ items.shift();
624
+ }
625
+ if (Buffer.byteLength(JSON.stringify(payload)) > payloadLimit)
626
+ throw new ApiError(422, 'assignment_context_limit', 'Required assignment metadata exceeds contextBytes; increase the bound or simplify the selected profile.');
627
+ }
628
+ return prefix + JSON.stringify(payload);
589
629
  }
590
630
  adapterContext(sessionId, body, key) {
591
631
  const session = this.store.get('sessions', sessionId), authority = this.store.private('session_authority', sessionId);
@@ -635,6 +675,11 @@ export class WorkflowEngine {
635
675
  throw new Error('pending_submission_missing');
636
676
  let submission = this.store.get('submissions', id);
637
677
  const artifact = this.store.get('artifacts', submission.artifactId), step = plan.definition.steps[plan.ordinal];
678
+ const pendingMessages = this.store.coordinator.db.prepare("SELECT id FROM engine_private WHERE scope='task_message' AND json_extract(body,'$.runId')=? AND json_extract(body,'$.delivered')=0").all(runId);
679
+ if (submission.kind === 'exit' && pendingMessages.length) {
680
+ await this.reject(runId, submission, [{ code: 'new_user_guidance', message: 'New user guidance arrived. Read the queued messages before completing the task.' }]);
681
+ return;
682
+ }
638
683
  if (submission.kind === 'exit' && !submission.workspaceRevision) {
639
684
  const revision = this.options.workspaces.captureRevision(runId);
640
685
  submission = { ...submission, workspaceRevision: revision, state: 'validating' };
@@ -755,7 +800,7 @@ export class WorkflowEngine {
755
800
  stepExecutionId: submission.stepExecutionId, leaseId: this.options.workspaces.lease(runId).id,
756
801
  workspaceRevisionId: submission.workspaceRevision.id, artifactId: artifact.id,
757
802
  artifact: { mediaType: artifact.document.mediaType, content: artifact.document.content, decoded },
758
- deadlineAt: Math.min(this.commands.now() + 30_000, plan.clock.deadlineAt ?? Infinity, plan.stepClocks[submission.stepExecutionId]?.deadlineAt ?? Infinity) }, this.signal(runId)));
803
+ deadlineAt: Math.min(this.commands.now() + (check.timeoutMs ?? 30_000), plan.clock.deadlineAt ?? Infinity, plan.stepClocks[submission.stepExecutionId]?.deadlineAt ?? Infinity) }, this.signal(runId)));
759
804
  if (result.status === 'infrastructure_error') {
760
805
  const retry = this.commands.retries.failure(episode, operation, { category: 'infrastructure', verifier: true, alreadyCharged: true,
761
806
  infrastructureRetries: this.store.get('runs', runId).policy.infrastructureRetries ?? 3,
@@ -869,7 +914,7 @@ export class WorkflowEngine {
869
914
  return;
870
915
  const artifact = this.store.get('artifacts', submission.artifactId);
871
916
  this.options.workspaces.accept({ runId, stepExecutionId: step.id, artifactId: artifact.id, revisionId: submission.workspaceRevision.id,
872
- expectedHead: submission.workspaceRevision.headCommit }, { onAdmittedSql: job => {
917
+ expectedHead: submission.workspaceRevision.headCommit, resultMode: this.commands.plan(runId).resultMode ?? 'commit' }, { onAdmittedSql: job => {
873
918
  this.store.setPrivate('workspace_continuation', job.id, { kind: 'accept', submissionId: submission.id, stepId: step.id });
874
919
  }, onCompletedSql: job => this.workspaceCompleted(job) });
875
920
  this.wake(runId);
@@ -885,17 +930,17 @@ export class WorkflowEngine {
885
930
  const submission = this.store.get('submissions', continuation.submissionId), artifact = this.store.get('artifacts', submission.artifactId);
886
931
  const eligible = submission.state !== 'superseded' && plan.steps[plan.ordinal]?.id === continuation.stepId;
887
932
  this.store.put('submissions', { ...submission, state: eligible ? 'accepted' : 'superseded' }, { runId: job.runId, parentId: submission.sessionId });
888
- this.store.put('artifacts', { ...artifact, state: eligible ? 'accepted' : 'superseded', commit: job.commit }, { runId: job.runId });
933
+ this.store.put('artifacts', { ...artifact, state: eligible ? 'accepted' : 'superseded', ...(job.resultMode === 'working_tree' ? {} : { commit: job.commit }) }, { runId: job.runId });
889
934
  if (eligible) {
890
935
  const step = this.store.get('steps', continuation.stepId), stepClock = plan.stepClocks[step.id];
891
936
  if (stepClock)
892
937
  plan.stepClocks[step.id] = checkpoint(stepClock, false, this.commands.now());
893
- this.store.put('steps', { ...step, state: 'succeeded', acceptedSubmissionId: submission.id, acceptedCommit: job.commit,
938
+ this.store.put('steps', { ...step, state: 'succeeded', acceptedSubmissionId: submission.id, acceptedRevisionId: job.revisionId, ...(job.resultMode === 'working_tree' ? {} : { acceptedCommit: job.commit }),
894
939
  ...(stepClock ? { timing: status(plan.stepClocks[step.id], true, this.commands.now()) } : {}) }, { runId: job.runId });
895
940
  plan.ordinal++;
896
941
  plan.stage = plan.ordinal >= plan.steps.length ? 'complete' : 'worker';
897
942
  }
898
- this.store.event(job.runId, 'artifact_committed', 'artifact', artifact.id, { commit: job.commit, submissionId: submission.id });
943
+ this.store.event(job.runId, job.resultMode === 'working_tree' ? 'artifact_accepted' : 'artifact_committed', 'artifact', artifact.id, { ...(job.resultMode === 'working_tree' ? { revisionId: job.revisionId } : { commit: job.commit }), submissionId: submission.id });
899
944
  }
900
945
  else {
901
946
  this.store.setPrivate('restore_completed', job.runId, { operationId: continuation.operationId ?? '', jobId: job.id });
@@ -1060,7 +1105,8 @@ export class WorkflowEngine {
1060
1105
  const run = this.store.get('runs', runId), plan = this.commands.plan(runId), now = this.commands.now();
1061
1106
  const stopped = terminal(run), paused = run.executionControl.status === 'paused';
1062
1107
  const blocked = run.pendingBlockIds.length > 0 || run.state === 'interrupted';
1063
- const running = !stopped && !paused && run.approvalWait.status !== 'waiting' && (!blocked || plan.timingPolicy.blockedTimeAccounting === 'count');
1108
+ const inputWaiting = this.options.inputWaiting?.(runId) ?? false;
1109
+ const running = !inputWaiting && !stopped && !paused && run.approvalWait.status !== 'waiting' && (!blocked || plan.timingPolicy.blockedTimeAccounting === 'count');
1064
1110
  plan.clock = checkpoint(plan.clock, running, now);
1065
1111
  const current = plan.steps[plan.ordinal], stepClock = current && plan.stepClocks[current.id];
1066
1112
  if (stepClock)
@@ -1612,6 +1658,15 @@ export class WorkflowEngine {
1612
1658
  this.operationState(operationId, 'running');
1613
1659
  await this.stopSessions(runId);
1614
1660
  this.reconcileStoppedModels(runId);
1661
+ try {
1662
+ this.options.reconcileCommands?.(runId);
1663
+ }
1664
+ catch {
1665
+ const block = this.commands.block(runId, 'external_workspace_change', 'Command recovery needs a current source digest and explicit preserve_changes or rollback resolution. Inspect the coding result and retry recover_run with commandResolution.', [], { recoveryAllowed: true });
1666
+ this.store.setPrivate('command_recovery_block', runId, { id: block.id });
1667
+ this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
1668
+ return;
1669
+ }
1615
1670
  if (this.work(runId).some(value => value.description !== 'Workspace effect requires read-only reconciliation')) {
1616
1671
  const block = this.commands.block(runId, 'verification_failed', 'Prior tool effects remain uncertain. Recovery cannot redispatch them or treat containment as completion.', []);
1617
1672
  this.operationState(operationId, 'waiting_for_decision', undefined, block.id);
@@ -1719,7 +1774,7 @@ export class WorkflowEngine {
1719
1774
  }
1720
1775
  this.supersede(runId);
1721
1776
  this.commands.updateRun(runId, { state: 'cancelled', completedAt: new Date(this.commands.now()).toISOString(),
1722
- executionControl: { status: 'paused', inFlightWork: [] } });
1777
+ executionControl: { ...this.store.get('runs', runId).executionControl, status: 'paused', pausedAt: new Date(this.commands.now()).toISOString(), inFlightWork: [] } });
1723
1778
  this.operationState(operationId, 'succeeded');
1724
1779
  this.updateClocks(runId);
1725
1780
  });
package/dist/src/main.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { pathToFileURL } from 'node:url';
2
2
  import { openDeployment, parseStartupArguments } from './server/deployment.js';
3
+ import { recordRuntimeBuild } from './cli/runtime-build.js';
3
4
  /** No environment/home discovery, ambient credentials, shell, auto-build, or
4
5
  * automatic provider login. Every input path must be explicitly supplied. */
5
6
  export async function main(argv = process.argv.slice(2)) {
6
- const deployment = await openDeployment(parseStartupArguments(argv));
7
+ const input = parseStartupArguments(argv);
8
+ const deployment = await openDeployment(input);
7
9
  let stopping;
8
10
  const stop = () => {
9
11
  stopping ??= deployment.close().catch(() => { process.stderr.write('Engine shutdown requires reconciliation.\n'); process.exitCode = 1; });
@@ -11,6 +13,7 @@ export async function main(argv = process.argv.slice(2)) {
11
13
  process.once('SIGINT', stop);
12
14
  process.once('SIGTERM', stop);
13
15
  try {
16
+ recordRuntimeBuild(input.stateDirectory);
14
17
  await deployment.listen();
15
18
  }
16
19
  catch (error) {
@@ -4,11 +4,13 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
4
4
  import { readOperatorToken } from '../config/deployment.js';
5
5
  import { createWorkflowServer } from './server.js';
6
6
  export async function main(argv = process.argv.slice(2)) {
7
- const { values } = parseArgs({ args: argv, options: { port: { type: 'string' }, 'operator-token-file': { type: 'string' } } });
7
+ const { values } = parseArgs({ args: argv, options: { port: { type: 'string' }, 'operator-token-file': { type: 'string' }, toolset: { type: 'string', default: 'coding' } } });
8
8
  const port = Number(values.port), file = values['operator-token-file'];
9
9
  if (!file || !values.port || !/^[0-9]+$/.test(values.port) || port < 1 || port > 65535)
10
10
  throw new Error('Invalid bridge configuration.');
11
- const server = createWorkflowServer(port, readOperatorToken(file));
11
+ if (!['coding', 'admin'].includes(values.toolset))
12
+ throw new Error('Invalid toolset.');
13
+ const server = createWorkflowServer(port, readOperatorToken(file), values.toolset);
12
14
  const close = () => { void server.close(); };
13
15
  process.stdin.once('end', close);
14
16
  process.stdin.once('error', close);
@@ -18,8 +18,9 @@ const resources = [
18
18
  ];
19
19
  const instructions = [
20
20
  'Operate the configured local Code60 Transmission Server with its operator workspace scope.',
21
- 'Discover runtimes and checks, register an authorized standalone Git repository, and publish profiles before workflows.',
22
- 'Workspaces must be existing standalone Git repositories with a real .git directory, at least one commit, no linked worktrees, no stale lock files, and no hardlinked files in .git. Do not run git init or git commit inside a sandbox that blocks file deletion (which leaves hardlinked tmp_obj_* files in .git); have the user prepare the repository directly on disk or clone with --no-hardlinks.',
21
+ 'For coding, check readiness then call start_coding_task with an existing repository or registered workspace and the task description. Results default to an uncommitted baseline-relative diff with command logs and check evidence.',
22
+ 'Git-aware workspaces support standalone repositories and linked worktrees with at least one commit, including staged and unstaged starting edits. Resolve unfinished Git operations before starting. Explicit sourceTracking:false retains the legacy standalone, clean-worktree requirements.',
23
+ 'For low-level workflows, discover runtimes and checks, register an authorized repository, and publish profiles before workflows.',
23
24
  'Use latestVersionId to pin profiles in workflow source and to select a workflow version in create_run.',
24
25
  'Call get_workflow_schema and get_workflow_example for authoring. The workflow version is the string "1".',
25
26
  'Call get_runtime_configuration and use the selected provider credentialReferences ID in credentialRefs.provider.',
@@ -84,7 +85,7 @@ async function callEngine(entry, args, port, token, signal) {
84
85
  detail: 'The bridge could not read an engine receipt. Retry a command with its original key and arguments.' }, true);
85
86
  }
86
87
  }
87
- export function createWorkflowServer(port, token) {
88
+ export function createWorkflowServer(port, token, toolset = 'admin') {
88
89
  const catalog = operatorCatalog();
89
90
  const discoveryTools = [
90
91
  { name: 'get_workflow_schema', description: 'Get the workflow language JSON Schema, including required fields and supported values.',
@@ -92,8 +93,21 @@ export function createWorkflowServer(port, token) {
92
93
  { name: 'get_workflow_example', description: 'Get a minimal valid workflow. Replace the worker profile version placeholder before validation.',
93
94
  inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } },
94
95
  ];
95
- const server = new Server({ name: 'code60-workflows', version: '0.1.0' }, { capabilities: { tools: {}, resources: {} }, instructions });
96
- server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [...discoveryTools, ...Array.from(catalog.values(), entry => entry.tool)] }));
96
+ const codingNames = new Set(['get_coding_readiness', 'start_coding_task', 'get_run', 'get_coding_task_result', 'list_run_events', 'send_task_message', 'list_task_questions', 'answer_task_question', 'list_run_approvals', 'get_approval', 'decide_approval', 'pause_run', 'resume_run', 'cancel_run', 'recover_run', 'get_operation']);
97
+ const managedControls = new Set(['pause_run', 'resume_run', 'cancel_run', ...(toolset === 'coding' ? ['decide_approval'] : [])]);
98
+ const codingInstructions = 'Use get_coding_readiness first, then start_coding_task with a task description, repositoryPath or workspaceId, and a stable idempotencyKey. Coding tasks run in the current folder, preserve existing edits, and leave the result uncommitted. Follow get_run/list_run_events; answer pending questions and inspect get_coding_task_result for the run-only diff and check evidence. If checks are absent the result explicitly says unverified. Send guidance with send_task_message. Low-level workflow administration remains available with --toolset admin.';
99
+ const server = new Server({ name: 'code60-workflows', version: '0.1.0' }, { capabilities: { tools: {}, resources: {} }, instructions: toolset === 'coding' ? codingInstructions : instructions });
100
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [
101
+ ...(toolset === 'admin' ? discoveryTools : []),
102
+ ...[...catalog.values()].filter(entry => toolset === 'admin' || codingNames.has(entry.tool.name)).map(entry => {
103
+ const tool = structuredClone(entry.tool);
104
+ if (managedControls.has(tool.name)) {
105
+ tool.inputSchema.required = tool.inputSchema.required?.filter(name => name !== 'ifMatch') ?? [];
106
+ tool.description += ' Omit ifMatch to let the bridge refresh versions during active execution; supply it for an exact conditional write.';
107
+ }
108
+ return tool;
109
+ }),
110
+ ] }));
97
111
  server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal }) => {
98
112
  if (params.name === 'get_workflow_schema' || params.name === 'get_workflow_example') {
99
113
  if (Object.keys(params.arguments ?? {}).length)
@@ -103,7 +117,24 @@ export function createWorkflowServer(port, token) {
103
117
  const entry = catalog.get(params.name);
104
118
  if (!entry)
105
119
  throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 operator tool.');
106
- return callEngine(entry, params.arguments ?? {}, port, token, signal);
120
+ const args = params.arguments ?? {};
121
+ if (args.ifMatch === undefined && managedControls.has(params.name)) {
122
+ return (async () => {
123
+ const target = params.name === 'decide_approval' ? catalog.get('get_approval') : catalog.get('get_run');
124
+ for (let attempt = 0;; attempt++) {
125
+ const read = await callEngine(target, params.name === 'decide_approval' ? { approvalId: args.approvalId } : { runId: args.runId }, port, token, signal);
126
+ const receipt = read.structuredContent;
127
+ if (read.isError || !receipt?.etag)
128
+ return read;
129
+ const written = await callEngine(entry, { ...args, ifMatch: receipt.etag }, port, token, signal);
130
+ // A failed precondition has no receipt or side effects. Retain the
131
+ // caller's key/body, and never retry an uncertain transport outcome.
132
+ if (written.structuredContent?.status !== 412 || attempt >= 15 || signal.aborted)
133
+ return written;
134
+ }
135
+ })();
136
+ }
137
+ return callEngine(entry, args, port, token, signal);
107
138
  });
108
139
  server.setRequestHandler(ListResourcesRequestSchema, () => ({ resources: resources.map(({ value, ...info }) => info) }));
109
140
  server.setRequestHandler(ReadResourceRequestSchema, ({ params }) => {
@@ -76,6 +76,7 @@ export class CodexEngineDriver {
76
76
  ...(this.options.createProviderTransport ? { createTransport: this.options.createProviderTransport } : {}),
77
77
  started: request => this.options.recordProviderStarted?.({ ...request, binding: launch.binding, providerId: provider.id,
78
78
  model: selected.model, effort: effort, credential: credential }),
79
+ diagnostic: diagnostic => this.options.recordProviderDiagnostic?.({ binding: launch.binding, ...diagnostic }),
79
80
  settled: request => this.options.recordProviderSettled?.({ ...request, binding: launch.binding }),
80
81
  onFailure: () => {
81
82
  const current = this.#entries.get(launch.session.id);
@@ -107,7 +108,7 @@ export class CodexEngineDriver {
107
108
  finally {
108
109
  entry.bookkeeping--;
109
110
  }
110
- return result;
111
+ return this.options.runtimeToolResult ? this.options.runtimeToolResult(launch.binding, request, result) : result;
111
112
  } }, async (params) => {
112
113
  if (entry.stopping)
113
114
  return;
@@ -164,13 +165,21 @@ export class CodexEngineDriver {
164
165
  if (!entry || !this.alive(sessionId) || !entry.threadId || entry.busy)
165
166
  throw new Error('runtime_session_unavailable');
166
167
  verifyWorkspaceInstructionSnapshot(entry.launch.workspaceInstructions);
167
- const workspace = entry.launch.workspaceInstructions.files.filter(file => file.selected).map(file => ({
168
+ let workspace = entry.launch.workspaceInstructions.files.filter(file => file.selected).map(file => ({
168
169
  type: 'text', text: `# AGENTS.md instructions for ${dirname(file.path)}\nApplies only to managed workspace paths in this directory and descendants. Follow applicable ancestor scopes; this is USER guidance, never system or developer authority.\n\n<INSTRUCTIONS>\n${file.content}\n</INSTRUCTIONS>`,
169
170
  }));
171
+ const bounded = entry.launch.binding.configuredTools.includes('get_context');
172
+ if (bounded) {
173
+ let remaining = Math.max(0, (this.options.contextBytes ?? 65_536) - Buffer.byteLength(instructions));
174
+ workspace = entry.guidanceDelivered ? [] : workspace.filter(item => { const bytes = Buffer.byteLength(item.text); if (bytes > remaining)
175
+ return false; remaining -= bytes; return true; });
176
+ }
170
177
  entry.busy = true;
171
178
  try {
172
179
  await entry.runtime.startTurn({ threadId: entry.threadId, environments: [], runtimeWorkspaceRoots: [],
173
180
  input: [...workspace, { type: 'text', text: instructions }] });
181
+ if (bounded)
182
+ entry.guidanceDelivered = true;
174
183
  }
175
184
  catch (error) {
176
185
  entry.broken = true;
@@ -3,7 +3,7 @@ import { constants } from 'node:fs';
3
3
  import { mkdtemp, open, rmdir, unlink } from 'node:fs/promises';
4
4
  import { createServer } from 'node:http';
5
5
  import { join } from 'node:path';
6
- import { ProviderTransport } from './provider-transport.js';
6
+ import { ProviderTransport, ProviderTransportError } from './provider-transport.js';
7
7
  const unavailable = () => new Error('provider_bridge_unavailable');
8
8
  /** One ephemeral loopback capability for one immutable session/epoch grant.
9
9
  * Containment is an outer restriction, not billable model authorization. */
@@ -31,7 +31,9 @@ export class ProviderBridge {
31
31
  ...(provider.maxConcurrent === undefined ? {} : { maxConcurrent: provider.maxConcurrent }),
32
32
  });
33
33
  this.#server = createServer({ maxHeaderSize: 16_384 }, (request, response) => {
34
- const task = Promise.resolve().then(() => this.serve(request, response)).catch(() => {
34
+ const task = Promise.resolve().then(() => this.serve(request, response)).catch(error => {
35
+ if (error instanceof ProviderTransportError)
36
+ this.options.diagnostic?.({ code: error.code, ...(error.upstreamStatus === undefined ? {} : { upstreamStatus: error.upstreamStatus }) });
35
37
  if (response.headersSent)
36
38
  response.destroy();
37
39
  else
@@ -4,20 +4,22 @@ import { checkServerIdentity, connect as tlsConnect } from "node:tls";
4
4
  import { digest, evaluatePolicy, jsonCopy, normalizeHost, validatePolicy } from "../broker/policy.js";
5
5
  import { numericAddress, PinnedDnsResolver } from "../tools/dns.js";
6
6
  const codes = new Set(["configuration", "closed", "capacity", "aborted", "timeout", "denied", "dns", "tls",
7
- "admission", "credential", "upstream", "content_type", "secret_echo", "body", "callback", "io"]);
7
+ "authentication", "rate_limited", "admission", "credential", "upstream", "content_type", "secret_echo", "body", "callback", "io"]);
8
8
  export class ProviderTransportError extends Error {
9
9
  failure;
10
+ upstreamStatus;
10
11
  code;
11
- constructor(failure) {
12
+ constructor(failure, upstreamStatus) {
12
13
  super(`provider_transport_${failure}`);
13
14
  this.failure = failure;
15
+ this.upstreamStatus = upstreamStatus;
14
16
  this.code = this.message;
15
17
  this.name = "ProviderTransportError";
16
18
  }
17
19
  }
18
- const failure = (value) => new ProviderTransportError(value);
20
+ const failure = (value, status) => new ProviderTransportError(value, status);
19
21
  const safe = (error, fallback) => error instanceof ProviderTransportError && codes.has(error.failure) && error.code === `provider_transport_${error.failure}`
20
- && error.message === error.code ? failure(error.failure) : failure(fallback);
22
+ && error.message === error.code ? failure(error.failure, error.upstreamStatus) : failure(fallback);
21
23
  const thenable = (value) => value !== null && (typeof value === "object" || typeof value === "function")
22
24
  && typeof value.then === "function";
23
25
  function synchronous(callback, code, ...args) {
@@ -290,7 +292,7 @@ export class ProviderTransport {
290
292
  check();
291
293
  const status = incoming.statusCode ?? 0;
292
294
  if (status < 200 || status >= 300)
293
- throw failure("upstream");
295
+ throw failure(status === 401 || status === 403 ? "authentication" : status === 429 ? "rate_limited" : "upstream", status);
294
296
  const rawType = incoming.headers["content-type"];
295
297
  const type = typeof rawType === "string" ? rawType.split(";")[0].trim().toLowerCase() : "";
296
298
  if ((type !== "application/json" && type !== "text/event-stream") ||