@tnunamak/dalan 0.0.0-stage → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
// Serializes first-open migration and cleanup across Store processes, not normal Store operations.
|
|
7
|
+
export function acquireSubscriptionStorage(file) {
|
|
8
|
+
if (file === ':memory:') return { key: randomBytes(32), release() {} };
|
|
9
|
+
const dir = `${fs.realpathSync(file)}.secrets`;
|
|
10
|
+
try { fs.mkdirSync(dir, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
11
|
+
// Persist the directory entry before any encrypted database transaction.
|
|
12
|
+
const parentFd = fs.openSync(path.dirname(dir), 'r'); try { fs.fsyncSync(parentFd); } finally { fs.closeSync(parentFd); }
|
|
13
|
+
const stat = fs.lstatSync(dir);
|
|
14
|
+
if (!stat.isDirectory() || (stat.mode & 0o777) !== 0o700 || (typeof process.getuid === 'function' && stat.uid !== process.getuid())) throw new Error('subscription storage directory is invalid');
|
|
15
|
+
const lockFile = path.join(dir, 'owner.sqlite');
|
|
16
|
+
try { fs.closeSync(fs.openSync(lockFile, 'wx', 0o600)); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
17
|
+
const lockStat = fs.lstatSync(lockFile);
|
|
18
|
+
if (!lockStat.isFile() || (lockStat.mode & 0o777) !== 0o600 || (typeof process.getuid === 'function' && lockStat.uid !== process.getuid())) throw new Error('subscription storage lock is invalid');
|
|
19
|
+
const lock = new DatabaseSync(lockFile);
|
|
20
|
+
try { lock.exec('PRAGMA busy_timeout=30000; BEGIN EXCLUSIVE'); } catch (error) { lock.close(); throw error; }
|
|
21
|
+
return {
|
|
22
|
+
loadKey(required) {
|
|
23
|
+
const keyFile = path.join(dir, 'storage.key');
|
|
24
|
+
if (!fs.existsSync(keyFile)) {
|
|
25
|
+
if (required) throw new Error('subscription storage key is missing');
|
|
26
|
+
const temp = path.join(dir, `.storage-key-${randomBytes(16).toString('hex')}.tmp`);
|
|
27
|
+
try {
|
|
28
|
+
const fd = fs.openSync(temp, 'wx', 0o600);
|
|
29
|
+
try { fs.writeFileSync(fd, randomBytes(32)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
30
|
+
try { fs.linkSync(temp, keyFile); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
31
|
+
} finally { fs.rmSync(temp, { force: true }); }
|
|
32
|
+
}
|
|
33
|
+
const keyStat = fs.lstatSync(keyFile);
|
|
34
|
+
if (!keyStat.isFile() || (keyStat.mode & 0o777) !== 0o600 || (typeof process.getuid === 'function' && keyStat.uid !== process.getuid())) throw new Error('subscription storage key is invalid');
|
|
35
|
+
const key = fs.readFileSync(keyFile);
|
|
36
|
+
if (key.length !== 32) throw new Error('subscription storage key is invalid');
|
|
37
|
+
// Also sync a recovered key's directory before committing encrypted rows.
|
|
38
|
+
const fd = fs.openSync(dir, 'r'); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
39
|
+
return key;
|
|
40
|
+
},
|
|
41
|
+
release() { lock.close(); },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class SubscriptionCodec {
|
|
46
|
+
constructor(key) { this.key = key; }
|
|
47
|
+
seal(value, context) {
|
|
48
|
+
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', this.key, iv);
|
|
49
|
+
cipher.setAAD(Buffer.from(context));
|
|
50
|
+
const data = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
|
51
|
+
return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join('.');
|
|
52
|
+
}
|
|
53
|
+
open(value, context) {
|
|
54
|
+
try {
|
|
55
|
+
const [version, nonce, tag, data, extra] = value.split('.');
|
|
56
|
+
if (version !== 'v1' || extra !== undefined || !nonce || !tag || data === undefined) throw new Error();
|
|
57
|
+
const iv = Buffer.from(nonce, 'base64url'), auth = Buffer.from(tag, 'base64url');
|
|
58
|
+
if (iv.length !== 12 || auth.length !== 16) throw new Error();
|
|
59
|
+
const cipher = createDecipheriv('aes-256-gcm', this.key, iv);
|
|
60
|
+
cipher.setAuthTag(auth); cipher.setAAD(Buffer.from(context));
|
|
61
|
+
return Buffer.concat([cipher.update(Buffer.from(data, 'base64url')), cipher.final()]).toString('utf8');
|
|
62
|
+
} catch { throw new Error('subscription storage is damaged or its key is invalid'); }
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/t3-audit.mjs
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { readEnv } from './env.mjs';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { redactSecrets } from './redaction.mjs';
|
|
4
|
+
|
|
5
|
+
const textFields = ['message', 'prompt', 'text'];
|
|
6
|
+
const sha256 = value => createHash('sha256').update(value).digest('hex');
|
|
7
|
+
|
|
8
|
+
// Free text is never stored: only the digest is kept. Only short mode-like
|
|
9
|
+
// values of a few fields stay readable; any other string is hashed.
|
|
10
|
+
const readableFields=new Set(['workspaceMode','status','mode','provider','thinkingEffort','permission','interactionMode','speedMode','environmentMode','projectPolicy']);
|
|
11
|
+
const enumShaped=value=>/^[a-z][a-z0-9_-]{0,23}$/.test(value)&&!/[0-9a-f]{32,}/i.test(value)&&!/^whsec_/i.test(value);
|
|
12
|
+
|
|
13
|
+
const auditFields=new Set(['threadId','projectId','cwd','workspaceMode','status','detail','turns','firstTurn','maxChars','timeoutMs','mode','wakeSettled','provider','model','thinkingEffort','permission','interactionMode','speedMode','environmentMode','projectPolicy','open','options']);
|
|
14
|
+
|
|
15
|
+
export function prepareT3Audit(tool, args = {}, worker='dot') {
|
|
16
|
+
const value = textFields.map(key => args[key]).find(item => typeof item === 'string');
|
|
17
|
+
const summary = {};
|
|
18
|
+
for(const [key,item] of Object.entries(args)) {
|
|
19
|
+
if(!auditFields.has(key)) continue;
|
|
20
|
+
const serialized=JSON.stringify(item);
|
|
21
|
+
const bounded=typeof item==='string'&&readableFields.has(key)&&enumShaped(item)&&redactSecrets(item).redacted===0?item
|
|
22
|
+
:typeof item==='boolean'||typeof item==='number'||item===null?item
|
|
23
|
+
:{sha256:sha256(serialized),bytes:Buffer.byteLength(serialized)};
|
|
24
|
+
if(Buffer.byteLength(JSON.stringify({...summary,[key]:bounded}))>2048) break;
|
|
25
|
+
summary[key]=bounded;
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
call_id: randomUUID(), tool, worker, args_summary: JSON.stringify(summary),
|
|
29
|
+
text_sha256: value === undefined ? null : sha256(value),
|
|
30
|
+
text_preview: null,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function initT3Audit(db) {
|
|
35
|
+
db.exec(`CREATE TABLE IF NOT EXISTS t3_audit (
|
|
36
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
+
at TEXT NOT NULL,
|
|
38
|
+
call_id TEXT NOT NULL,
|
|
39
|
+
subject TEXT NOT NULL,
|
|
40
|
+
tool TEXT NOT NULL,
|
|
41
|
+
args_summary TEXT NOT NULL,
|
|
42
|
+
text_sha256 TEXT,
|
|
43
|
+
text_preview TEXT,
|
|
44
|
+
result_status TEXT NOT NULL,
|
|
45
|
+
t3_ids TEXT NOT NULL DEFAULT '{}'
|
|
46
|
+
);
|
|
47
|
+
CREATE INDEX IF NOT EXISTS t3_audit_at ON t3_audit(at);
|
|
48
|
+
CREATE TRIGGER IF NOT EXISTS t3_audit_no_update BEFORE UPDATE ON t3_audit BEGIN SELECT RAISE(ABORT, 't3 audit is append-only'); END;
|
|
49
|
+
CREATE TRIGGER IF NOT EXISTS t3_audit_no_delete BEFORE DELETE ON t3_audit BEGIN SELECT RAISE(ABORT, 't3 audit is append-only'); END;`);
|
|
50
|
+
if(!db.prepare('PRAGMA table_info(t3_audit)').all().some(column=>column.name==='worker')) db.exec("ALTER TABLE t3_audit ADD COLUMN worker TEXT NOT NULL DEFAULT 'dot'");
|
|
51
|
+
// Old rows have no trustworthy worker attribution. Keep them as history, never
|
|
52
|
+
// charge them to a live principal merely because the migration default is 'dot'.
|
|
53
|
+
if(!db.prepare('PRAGMA table_info(t3_audit)').all().some(column=>column.name==='budget_version')) db.exec('ALTER TABLE t3_audit ADD COLUMN budget_version INTEGER NOT NULL DEFAULT 0');
|
|
54
|
+
db.exec('CREATE INDEX IF NOT EXISTS t3_audit_principal_at ON t3_audit(worker,subject,at) WHERE budget_version=1');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// One start or denial charges one call. Final records always fit an admitted
|
|
58
|
+
// call. Persisted rolling windows survive reconnects/restarts without deleting
|
|
59
|
+
// append-only history or charging another subject on the same worker.
|
|
60
|
+
export function admitT3Audit(db,worker,subject,{now=Date.now(),env=process.env}={}) {
|
|
61
|
+
if(typeof subject!=='string'||!subject) throw new Error('T3 audit requires an authenticated subject');
|
|
62
|
+
const limit=(name,fallback)=>{
|
|
63
|
+
const value=readEnv(name,env)===undefined?fallback:Number(readEnv(name,env));
|
|
64
|
+
if(!Number.isSafeInteger(value)||value<1) throw new Error(`invalid ${name}: expected a positive safe integer`);
|
|
65
|
+
return value;
|
|
66
|
+
};
|
|
67
|
+
const perMinute=limit('DALAN_T3_CALLS_PER_MINUTE',60),perDay=limit('DALAN_T3_CALLS_PER_DAY',10000);
|
|
68
|
+
const count=db.prepare(`SELECT count(*) n FROM t3_audit
|
|
69
|
+
WHERE worker=? AND subject=? AND budget_version=1 AND at>? AND at<=?
|
|
70
|
+
AND (result_status='started' OR result_status LIKE 'denied:%')`);
|
|
71
|
+
const until=new Date(now).toISOString();
|
|
72
|
+
const recent=count.get(worker,subject,new Date(now-60000).toISOString(),until).n;
|
|
73
|
+
const daily=count.get(worker,subject,new Date(now-86400000).toISOString(),until).n;
|
|
74
|
+
if(recent>=perMinute||daily>=perDay) throw new Error('t3_rate_limit: principal call budget exhausted (rolling 60-second/24-hour windows)');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Result ids come from a remote service: keep plain id-shaped values readable, hash anything else.
|
|
78
|
+
// An unbroken 24+ character alphanumeric run is the shape of an opaque credential, so it is hashed too.
|
|
79
|
+
const plainId=value=>typeof value==='string'&&value.length<=512&&/^[A-Za-z0-9._:%-]+$/.test(value)&&!/[0-9a-f]{32,}/i.test(value)&&!/[A-Za-z0-9]{24,}/.test(value)&&!/^whsec_/i.test(value)&&redactSecrets(value).redacted===0;
|
|
80
|
+
const safeIds=value=>Array.isArray(value)?value.map(safeIds)
|
|
81
|
+
:typeof value==='string'?(plainId(value)?value:`sha256:${sha256(value)}`)
|
|
82
|
+
:value&&typeof value==='object'?safeKeys(value)
|
|
83
|
+
:value;
|
|
84
|
+
|
|
85
|
+
// Keys come from the same remote service and get the same check. A hashed key that meets an existing name gets a
|
|
86
|
+
// numbered suffix, so no entry is lost.
|
|
87
|
+
function safeKeys(value) {
|
|
88
|
+
const out={};
|
|
89
|
+
for(const [key,item] of Object.entries(value)) {
|
|
90
|
+
const base=plainId(key)?key:`sha256:${sha256(key)}`;
|
|
91
|
+
let name=base,n=2;
|
|
92
|
+
while(Object.hasOwn(out,name)) name=`${base} (${n++})`;
|
|
93
|
+
out[name]=safeIds(item);
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function appendT3Audit(db, entry, subject, resultStatus, result) {
|
|
99
|
+
const ids = result?._audit_ids && typeof result._audit_ids === 'object'
|
|
100
|
+
? result._audit_ids
|
|
101
|
+
: result?.t3_ids && typeof result.t3_ids === 'object'
|
|
102
|
+
? result.t3_ids
|
|
103
|
+
: result && typeof result === 'object'
|
|
104
|
+
? Object.fromEntries([
|
|
105
|
+
['threadIds', result.threadId ? [result.threadId] : []],
|
|
106
|
+
['projectIds', result.projectId ? [result.projectId] : []],
|
|
107
|
+
['runIds', result.runId ? [result.runId] : []],
|
|
108
|
+
['messageIds', result.messageId ? [result.messageId] : []],
|
|
109
|
+
].filter(([, items]) => items.length))
|
|
110
|
+
: {};
|
|
111
|
+
db.prepare(`INSERT INTO t3_audit(at,call_id,subject,tool,args_summary,text_sha256,text_preview,result_status,t3_ids,worker,budget_version)
|
|
112
|
+
VALUES(?,?,?,?,?,?,?,?,?,?,1)`).run(new Date().toISOString(), entry.call_id, subject, entry.tool,
|
|
113
|
+
entry.args_summary, entry.text_sha256, entry.text_preview, resultStatus, JSON.stringify(safeIds(ids)), entry.worker??'dot');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function listT3Audit(db, since) {
|
|
117
|
+
if (since && (!Number.isFinite(Date.parse(since)) || !/^\d{4}-\d\d-\d\dT/.test(since))) throw new Error('invalid audit since');
|
|
118
|
+
return db.prepare(`SELECT * FROM t3_audit WHERE at >= ? ORDER BY id DESC`).all(since ? new Date(since).toISOString() : '0000')
|
|
119
|
+
.map(row => ({...row, args_summary: JSON.parse(row.args_summary), t3_ids: JSON.parse(row.t3_ids)}));
|
|
120
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { callT3, listArgs, readArgs, createArgs, threadSendArgs, waitArgs } from './t3.mjs';
|
|
2
|
+
|
|
3
|
+
const seconds = ms => Math.max(1, Math.min(115, Math.ceil((ms ?? 120000) / 1000)));
|
|
4
|
+
|
|
5
|
+
function setArgs(a) {
|
|
6
|
+
const args=['threads','set','--thread',a.threadId];
|
|
7
|
+
for (const [flag,value] of [
|
|
8
|
+
['--provider',a.provider],
|
|
9
|
+
['--model',a.model],
|
|
10
|
+
['--thinking-effort',a.thinkingEffort],
|
|
11
|
+
['--permission',a.permission],
|
|
12
|
+
['--interaction-mode',a.interactionMode],
|
|
13
|
+
['--speed-mode',a.speedMode]
|
|
14
|
+
]) if(value) args.push(flag,String(value));
|
|
15
|
+
for (const option of a.options ?? []) args.push('--option', String(option));
|
|
16
|
+
return args;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function idsFrom(value) {
|
|
20
|
+
const thread=value?.thread, project=value?.project, message=value?.message;
|
|
21
|
+
const addUnique=(array,item)=>{ if(item&&!array.includes(item)) array.push(item); };
|
|
22
|
+
const ids={threadIds:[],projectIds:[],runIds:[],messageIds:[]};
|
|
23
|
+
addUnique(ids.threadIds,thread?.id);
|
|
24
|
+
addUnique(ids.projectIds,project?.id ?? thread?.projectId);
|
|
25
|
+
addUnique(ids.messageIds,message?.messageId);
|
|
26
|
+
addUnique(ids.runIds,thread?.activeRun?.runId ?? thread?.latestRun?.runId);
|
|
27
|
+
for (const item of value?.threads ?? []) {
|
|
28
|
+
addUnique(ids.threadIds,item.id);
|
|
29
|
+
addUnique(ids.projectIds,item.projectId);
|
|
30
|
+
addUnique(ids.runIds,item.activeRun?.runId ?? item.latestRun?.runId);
|
|
31
|
+
}
|
|
32
|
+
for (const item of value?.projects ?? []) addUnique(ids.projectIds,item.id);
|
|
33
|
+
for (const item of thread?.turns ?? []) {
|
|
34
|
+
addUnique(ids.runIds,item.runId);
|
|
35
|
+
addUnique(ids.messageIds,item.finalMessageId);
|
|
36
|
+
}
|
|
37
|
+
return Object.fromEntries(Object.entries(ids).filter(([,items])=>items.length));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function withIds(data) { return {...data, _audit_ids: idsFrom(data)}; }
|
|
41
|
+
|
|
42
|
+
// `t3code threads list` can return large records. The worker polls it, so the list returns the newest threads (updatedAt desc)
|
|
43
|
+
// in a compact shape: at most `limit` entries and at most `budget` bytes of serialized thread entries, plus total and
|
|
44
|
+
// per-project counts.
|
|
45
|
+
export const THREAD_LIST_LIMIT=50, THREAD_LIST_BUDGET=16000;
|
|
46
|
+
const PROJECT_LIMIT=20, TITLE_MAX=120, SHORT_MAX=80;
|
|
47
|
+
const clip=(text,max)=>typeof text==='string'&&text.length>max?text.slice(0,max-1)+'\u2026':text??null;
|
|
48
|
+
const short=text=>typeof text==='string'&&text&&text.length<=SHORT_MAX?text:undefined;
|
|
49
|
+
const compactThread=t=>({id:t.id,title:clip(t.title,TITLE_MAX),projectId:t.projectId??null,status:t.status??null,runStatus:t.runStatus??null,
|
|
50
|
+
...(t.activityRunStatus!=null?{activityRunStatus:t.activityRunStatus}:{}),updatedAt:t.updatedAt??null,latestUserMessageAt:t.latestUserMessageAt??null,
|
|
51
|
+
pendingRuntimeRequest:t.pendingRuntimeRequest!=null&&t.pendingRuntimeRequest!==false,branch:short(t.branch),worktreePath:short(t.worktreePath)});
|
|
52
|
+
export function compactThreadList(data,{limit=THREAD_LIST_LIMIT,budget=THREAD_LIST_BUDGET}={}) {
|
|
53
|
+
const threads=(Array.isArray(data?.threads)?data.threads:[]).toSorted((a,b)=>String(b.updatedAt??'').localeCompare(String(a.updatedAt??''))||String(a.id).localeCompare(String(b.id)));
|
|
54
|
+
const shown=[];
|
|
55
|
+
for(let i=0,used=0;i<threads.length&&shown.length<limit;i++) {
|
|
56
|
+
const entry=compactThread(threads[i]), bytes=Buffer.byteLength(JSON.stringify(entry))+1;
|
|
57
|
+
if(shown.length&&used+bytes>budget) break;
|
|
58
|
+
shown.push(entry); used+=bytes;
|
|
59
|
+
}
|
|
60
|
+
const titles=new Map((Array.isArray(data?.projects)?data.projects:[]).map(p=>[p.id,p.title]));
|
|
61
|
+
const counts=new Map();
|
|
62
|
+
for(const t of threads) counts.set(t.projectId??null,(counts.get(t.projectId??null)??0)+1);
|
|
63
|
+
const projects=[...counts].sort((a,b)=>b[1]-a[1]||String(a[0]).localeCompare(String(b[0]))).slice(0,PROJECT_LIMIT).map(([id,count])=>({id,title:clip(titles.get(id),TITLE_MAX),count}));
|
|
64
|
+
return {threads:shown,total:threads.length,shown:shown.length,truncated:threads.length>shown.length,projects,...(counts.size>projects.length?{projects_total:counts.size}:{}),
|
|
65
|
+
hint:'narrow with projectId or cwd; full paging after a catalog update'};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function cwdForProject(a) {
|
|
69
|
+
if (!a.projectId) return a.cwd;
|
|
70
|
+
const data = await callT3(['projects','list']);
|
|
71
|
+
const project = data.projects?.find(item => item.id === a.projectId);
|
|
72
|
+
if (!project) throw new Error('project not found');
|
|
73
|
+
if (a.cwd && a.cwd !== project.workspaceRoot) throw new Error('projectId and cwd disagree');
|
|
74
|
+
return project.workspaceRoot;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function runT3Tool(name, a) {
|
|
78
|
+
switch(name) {
|
|
79
|
+
case 't3_thread_list':
|
|
80
|
+
return withIds(compactThreadList(await callT3(listArgs({cwd:a.cwd,project:a.projectId,status:a.status,workspace_mode:a.workspaceMode}))));
|
|
81
|
+
case 't3_thread_read':
|
|
82
|
+
return withIds(await callT3(readArgs({thread:a.threadId,detail:a.detail??'messages',turns:a.turns??20,first_turn:a.firstTurn,max_chars:a.maxChars??12000})));
|
|
83
|
+
case 't3_thread_create':
|
|
84
|
+
return withIds(await callT3(createArgs({cwd:await cwdForProject(a),workspace_mode:a.workspaceMode,project_policy:a.projectPolicy,open:a.open,provider:a.provider,model:a.model,speed_mode:a.speedMode,thinking_effort:a.thinkingEffort,env_mode:a.environmentMode,permission:a.permission,interaction_mode:a.interactionMode,options:a.options,wait:false,detail:'answers',max_chars:4000}),a.prompt));
|
|
85
|
+
case 't3_thread_send':
|
|
86
|
+
return withIds(await callT3(threadSendArgs({thread:a.threadId,if_busy:a.mode??'queue',provider:a.provider,model:a.model,speed_mode:a.speedMode,thinking_effort:a.thinkingEffort,permission:a.permission,interaction_mode:a.interactionMode,options:a.options,wake_settled:a.wakeSettled,wait:false,detail:'answers',max_chars:4000}),a.message));
|
|
87
|
+
case 't3_thread_wait': {
|
|
88
|
+
const timeout=seconds(a.timeoutMs);
|
|
89
|
+
try {
|
|
90
|
+
return withIds(await callT3(waitArgs({thread:a.threadId,timeout,detail:a.detail??'answers',max_chars:a.maxChars??12000}),'',{timeoutMs:timeout*1000}));
|
|
91
|
+
} catch(error) {
|
|
92
|
+
if(error.t3ErrorCode!=='THREAD_WAIT_TIMEOUT' && !error.message.startsWith('t3code timeout after ')) throw error;
|
|
93
|
+
const partial=await callT3(readArgs({thread:a.threadId,detail:a.detail??'answers',turns:1,max_chars:a.maxChars??12000}),'',{timeoutMs:5000});
|
|
94
|
+
return withIds({still_running:true,timeout_seconds:timeout,partial,error:error.message});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
case 't3_thread_set':
|
|
98
|
+
return withIds(await callT3(setArgs(a)));
|
|
99
|
+
default:
|
|
100
|
+
throw new Error('unknown t3 tool');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { readEnv } from './env.mjs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { promisify } from 'node:util';
|
|
8
|
+
|
|
9
|
+
const execFileAsync = promisify(execFile);
|
|
10
|
+
const protocolVersion = 2;
|
|
11
|
+
const activeStatuses = new Set(['preparing', 'starting', 'running', 'waiting']);
|
|
12
|
+
// Created only for authenticated HTTP reads/ticket issuance before dispatch.
|
|
13
|
+
export class T3PreDispatchAuthError extends Error {}
|
|
14
|
+
|
|
15
|
+
export function resultDeliveryIds(jobId, effectId) {
|
|
16
|
+
if (typeof jobId !== 'string' || !jobId || typeof effectId !== 'string' || !effectId) {
|
|
17
|
+
throw new Error('T3 result delivery requires job and effect IDs');
|
|
18
|
+
}
|
|
19
|
+
const digest = createHash('sha256').update(JSON.stringify([jobId, effectId])).digest('hex');
|
|
20
|
+
return { commandId: `dot-bridge:${digest}`, messageId: `dot-bridge-message:${digest}` };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function loopbackOrigin(value) {
|
|
24
|
+
const url = new URL(value);
|
|
25
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) throw new Error('T3 transport requires a loopback origin');
|
|
26
|
+
return url.origin;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function t3Home() {
|
|
30
|
+
return path.resolve(process.env.T3CODE_HOME || path.join(os.homedir(), '.t3'));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function runtime(home) {
|
|
34
|
+
for (const name of ['userdata', 'dev']) {
|
|
35
|
+
try {
|
|
36
|
+
const value = JSON.parse(await readFile(path.join(home,name,'server-runtime.json'), 'utf8'));
|
|
37
|
+
if (value.version === 1 && typeof value.origin === 'string' && typeof value.serverVersion === 'string') {
|
|
38
|
+
const origin = loopbackOrigin(value.origin);
|
|
39
|
+
const response = await fetch(`${origin}/.well-known/t3/environment`, { signal: AbortSignal.timeout(2500) });
|
|
40
|
+
if (!response.ok) continue;
|
|
41
|
+
const descriptor = await response.json();
|
|
42
|
+
if (descriptor.orchestrationProtocolVersion !== protocolVersion || descriptor.serverVersion !== value.serverVersion || typeof descriptor.environmentId !== 'string') continue;
|
|
43
|
+
return { origin, serverVersion: value.serverVersion, environmentId: descriptor.environmentId, baseDir: home };
|
|
44
|
+
}
|
|
45
|
+
} catch {}
|
|
46
|
+
}
|
|
47
|
+
throw new Error('T3 local orchestrator V2 is unavailable');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function cliCommand(serverVersion) {
|
|
51
|
+
const command = readEnv('DALAN_T3_COMMAND') || 't3';
|
|
52
|
+
const version = await execFileAsync(command, ['--version'], { timeout: 5000 }).catch(() => null);
|
|
53
|
+
if (!version || !version.stdout.includes(serverVersion)) throw new Error('matching T3 auth command is unavailable');
|
|
54
|
+
return command;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function issueSession(command, baseDir) {
|
|
58
|
+
let stdout;
|
|
59
|
+
try {
|
|
60
|
+
({ stdout } = await execFileAsync(command, [
|
|
61
|
+
'auth', 'session', 'issue', '--json', '--ttl', '2m', '--label', 'dot-bridge-result-delivery',
|
|
62
|
+
'--subject', 'dot-bridge', '--base-dir', baseDir,
|
|
63
|
+
'--scope', 'orchestration:read', '--scope', 'orchestration:operate',
|
|
64
|
+
], { timeout: 15000, maxBuffer: 64 * 1024 }));
|
|
65
|
+
} catch { throw new Error('T3 auth session issue failed'); }
|
|
66
|
+
let issued;
|
|
67
|
+
try { issued = JSON.parse(stdout); } catch { throw new Error('T3 auth returned invalid JSON'); }
|
|
68
|
+
if (typeof issued.sessionId !== 'string' || typeof issued.token !== 'string') throw new Error('T3 auth returned an invalid session');
|
|
69
|
+
return issued;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function revokeSession(command, baseDir, sessionId) {
|
|
73
|
+
await execFileAsync(command, ['auth', 'session', 'revoke', sessionId, '--base-dir', baseDir], { timeout: 10000 }).catch(() => {});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function authenticatedRequest(origin, token, pathname, method = 'GET') {
|
|
77
|
+
const response = await fetch(new URL(pathname, origin), {
|
|
78
|
+
method,
|
|
79
|
+
headers: { authorization: `Bearer ${token}`, 'x-t3-orchestration-protocol': String(protocolVersion) },
|
|
80
|
+
signal: AbortSignal.timeout(10000),
|
|
81
|
+
});
|
|
82
|
+
if(response.status===401) throw new T3PreDispatchAuthError('T3 rejected authentication before message dispatch');
|
|
83
|
+
if (!response.ok) throw new Error(`T3 read failed with HTTP ${response.status}`);
|
|
84
|
+
return response.json();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function dispatchMode(projection) {
|
|
88
|
+
const active = projection.runs.filter(run => activeStatuses.has(run.status));
|
|
89
|
+
const activeRun = active.sort((a, b) => b.ordinal - a.ordinal)[0];
|
|
90
|
+
if (activeRun) return { type: 'steer_active', targetRunId: activeRun.id };
|
|
91
|
+
if (projection.runs.some(run => run.status === 'queued' || run.queuePosition != null)) return { type: 'queue_after_active' };
|
|
92
|
+
return { type: 'start_immediately' };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function rpcRequest(url, tag, payload) {
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const socket = new WebSocket(url);
|
|
98
|
+
socket.binaryType = 'arraybuffer';
|
|
99
|
+
const requestId = '1';
|
|
100
|
+
const timer = setTimeout(() => finish(new Error('T3 dispatch timed out')), 15000);
|
|
101
|
+
let done = false;
|
|
102
|
+
const finish = (error, value) => {
|
|
103
|
+
if (done) return;
|
|
104
|
+
done = true;
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
socket.close();
|
|
107
|
+
error ? reject(error) : resolve(value);
|
|
108
|
+
};
|
|
109
|
+
socket.addEventListener('open', () => socket.send(JSON.stringify({ _tag: 'Request', id: requestId, tag, payload, headers: [] })));
|
|
110
|
+
socket.addEventListener('message', event => {
|
|
111
|
+
try {
|
|
112
|
+
const messages = JSON.parse(typeof event.data === 'string' ? event.data : new TextDecoder().decode(event.data));
|
|
113
|
+
for (const message of (Array.isArray(messages) ? messages : [messages])) {
|
|
114
|
+
if (message._tag === 'Exit' && String(message.requestId) === requestId) {
|
|
115
|
+
if (message.exit?._tag !== 'Success') return finish(new Error('T3 rejected message dispatch'));
|
|
116
|
+
return finish(null, message.exit.value);
|
|
117
|
+
}
|
|
118
|
+
if (message._tag === 'Defect' || message._tag === 'ClientProtocolError') return finish(new Error('T3 WebSocket protocol error'));
|
|
119
|
+
}
|
|
120
|
+
} catch { finish(new Error('T3 returned an invalid WebSocket response')); }
|
|
121
|
+
});
|
|
122
|
+
socket.addEventListener('error', () => finish(new Error('T3 WebSocket request failed')));
|
|
123
|
+
socket.addEventListener('close', () => { if (!done) finish(new Error('T3 closed before dispatch response')); });
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function dispatchWithSession(origin, token, threadId, message, ids, options) {
|
|
128
|
+
const detail = await authenticatedRequest(origin, token, `/api/orchestration/threads/${encodeURIComponent(threadId)}`);
|
|
129
|
+
const projection = detail?.projection;
|
|
130
|
+
if (projection?.thread?.id !== threadId) throw new Error('T3 thread binding changed');
|
|
131
|
+
const issued = await authenticatedRequest(origin, token, '/api/auth/websocket-ticket', 'POST');
|
|
132
|
+
if (typeof issued.ticket !== 'string' || !issued.ticket) throw new Error('T3 did not issue a WebSocket ticket');
|
|
133
|
+
const wsUrl = new URL('/ws', origin);
|
|
134
|
+
wsUrl.protocol = wsUrl.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
135
|
+
wsUrl.searchParams.set('wsTicket', issued.ticket);
|
|
136
|
+
wsUrl.searchParams.set('orchestrationProtocol', String(protocolVersion));
|
|
137
|
+
const command = {
|
|
138
|
+
type: 'message.dispatch', ...ids, threadId, messageId: ids.messageId,
|
|
139
|
+
text: message, attachments: [], createdBy: 'user', creationSource: 'web',
|
|
140
|
+
dispatchMode: options.dispatchMode ?? dispatchMode(projection),
|
|
141
|
+
};
|
|
142
|
+
return rpcRequest(wsUrl, 'orchestration.dispatchCommand', command);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function dispatchT3Result(threadId, environmentId, jobId, effectId, message, options = {}) {
|
|
146
|
+
const ids = resultDeliveryIds(jobId, effectId);
|
|
147
|
+
const home = await t3Home();
|
|
148
|
+
const target = await runtime(home);
|
|
149
|
+
if (target.environmentId !== environmentId) throw new Error('T3 environment binding changed');
|
|
150
|
+
const command = await cliCommand(target.serverVersion);
|
|
151
|
+
const session = await issueSession(command, target.baseDir);
|
|
152
|
+
try {
|
|
153
|
+
options.onSession?.(session.sessionId);
|
|
154
|
+
return await dispatchWithSession(target.origin, session.token, threadId, message, ids, options);
|
|
155
|
+
} finally {
|
|
156
|
+
await revokeSession(command, target.baseDir, session.sessionId);
|
|
157
|
+
}
|
|
158
|
+
}
|
package/src/t3.mjs
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { readEnv } from './env.mjs';
|
|
2
|
+
import { parseJsonBody, safeDiagnostic } from './diagnostic.mjs';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { dispatchT3Result, T3PreDispatchAuthError } from './t3-transport.mjs';
|
|
8
|
+
|
|
9
|
+
export const sendArgs = (threadId,kind) => ['threads','send','--thread',threadId,'--stdin','--if-busy','steer'];
|
|
10
|
+
export const marker = id => `[dot-bridge event ${id}]`;
|
|
11
|
+
// A typed pre-dispatch HTTP401 or the legacy CLI's definite auth refusal is safe to retry.
|
|
12
|
+
export const preAcceptAuthRejection = error => error instanceof T3PreDispatchAuthError || /invalid session credential/i.test(error?.message ?? '');
|
|
13
|
+
export const authRetryMax = () => { const n=Number(readEnv('DALAN_T3_AUTH_RETRY_MAX')); return Number.isInteger(n)&&n>=1?n:8; };
|
|
14
|
+
export const t3Origin = 'http://127.0.0.1:3773';
|
|
15
|
+
|
|
16
|
+
export function textSummary(text) {
|
|
17
|
+
if (typeof text !== 'string') return { sha256: null, first200: null };
|
|
18
|
+
return { sha256: createHash('sha256').update(text).digest('hex'), first200: text.slice(0, 200) };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The one place that decides which binary talks to T3 (test mode may point at a fake).
|
|
22
|
+
export const t3Bin = () => (process.env.NODE_ENV==='test'||readEnv('DALAN_T3_DRY_RUN')==='1')&&readEnv('DALAN_T3CODE_BIN')?readEnv('DALAN_T3CODE_BIN'):'t3code';
|
|
23
|
+
// Is T3 usable on this host: the binary resolves (an absolute path as-is, else a PATH search for an executable file). No spawn, no T3 call.
|
|
24
|
+
export function t3Available(bin=t3Bin(),pathVar=process.env.PATH??'') {
|
|
25
|
+
const executable=file=>{ try { fs.accessSync(file,fs.constants.X_OK); return fs.statSync(file).isFile(); } catch { return false; } };
|
|
26
|
+
return bin.includes('/')?executable(bin):pathVar.split(path.delimiter).some(dir=>dir&&executable(path.join(dir,bin)));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function callT3(args,input='',options={}) {
|
|
30
|
+
if (options.resultDelivery) {
|
|
31
|
+
const { threadId, environmentId, jobId, effectId } = options.resultDelivery;
|
|
32
|
+
return dispatchT3Result(threadId,environmentId,jobId,effectId,input,options.resultDelivery.transportOptions);
|
|
33
|
+
}
|
|
34
|
+
const timeoutMs = options.timeoutMs ?? 15000;
|
|
35
|
+
const maxOutputBytes = options.maxOutputBytes ?? 5 * 1024 * 1024;
|
|
36
|
+
return new Promise((resolve,reject)=>{
|
|
37
|
+
const bin=t3Bin();
|
|
38
|
+
const child=spawn(bin,['--json','--origin',t3Origin,...args],{stdio:['pipe','pipe','pipe'],detached:process.platform!=='win32'});
|
|
39
|
+
const processGroupId=process.platform!=='win32'?child.pid:null;
|
|
40
|
+
let output='',error='',spawnError=null,limitError=null;
|
|
41
|
+
let outputBytes=0;
|
|
42
|
+
let timedOut=false;
|
|
43
|
+
const killTree=()=>{
|
|
44
|
+
try { if(processGroupId) process.kill(-processGroupId,'SIGKILL'); else child.kill('SIGKILL'); }
|
|
45
|
+
catch(error) { if(error.code!=='ESRCH') try{child.kill('SIGKILL');}catch{} }
|
|
46
|
+
};
|
|
47
|
+
const timer=setTimeout(()=>{timedOut=true;killTree();},timeoutMs);
|
|
48
|
+
const capture=(which,b)=>{
|
|
49
|
+
if(outputBytes+b.length>maxOutputBytes) { limitError=new Error(`t3code output exceeded ${maxOutputBytes} bytes`); killTree(); return; }
|
|
50
|
+
outputBytes+=b.length;
|
|
51
|
+
if(which==='stdout') output+=b; else error+=b;
|
|
52
|
+
};
|
|
53
|
+
child.stdout.on('data',b=>capture('stdout',b));
|
|
54
|
+
child.stderr.on('data',b=>capture('stderr',b));
|
|
55
|
+
child.on('error',error=>{spawnError=error;});
|
|
56
|
+
child.stdin.on('error',()=>{});
|
|
57
|
+
child.on('close',async (code,signal)=>{
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
if(processGroupId) {
|
|
60
|
+
try { process.kill(-processGroupId,'SIGKILL'); } catch(error) { if(error.code!=='ESRCH') return reject(error); }
|
|
61
|
+
try { await settleProcessGroup(processGroupId); } catch(error) { return reject(error); }
|
|
62
|
+
}
|
|
63
|
+
if(timedOut)return reject(new Error(`t3code timeout after ${timeoutMs}ms`));
|
|
64
|
+
if(limitError)return reject(limitError);
|
|
65
|
+
if(spawnError)return reject(spawnError);
|
|
66
|
+
if(code!==0) {
|
|
67
|
+
let parsed;
|
|
68
|
+
try { parsed=JSON.parse(output||error); } catch {}
|
|
69
|
+
const outcome=signal?`signal ${signal}`:`exit ${code}`;
|
|
70
|
+
const err=new Error(`t3code ${outcome}: ${safeDiagnostic(error||output,2000)}`);
|
|
71
|
+
err.exitCode=code;
|
|
72
|
+
if(signal) err.signal=signal;
|
|
73
|
+
if(parsed?.error?.code) err.t3ErrorCode=parsed.error.code;
|
|
74
|
+
return reject(err);
|
|
75
|
+
}
|
|
76
|
+
try {const parsed=parseJsonBody(output,'t3code output');if(!parsed.ok){const err=new Error(safeDiagnostic(parsed.error?.message||'t3code error',2000));if(parsed.error?.code)err.t3ErrorCode=parsed.error.code;throw err;}resolve(parsed.data);}
|
|
77
|
+
catch(e){reject(e);}
|
|
78
|
+
});
|
|
79
|
+
child.stdin.end(input);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function settleProcessGroup(groupId) {
|
|
84
|
+
// Linux /proc distinguishes non-running zombies from executing group members;
|
|
85
|
+
// other POSIX systems conservatively wait for the group ID to disappear.
|
|
86
|
+
const groupHasExecutingProcess=()=>{
|
|
87
|
+
if(process.platform==='linux') {
|
|
88
|
+
for(const entry of fs.readdirSync('/proc')) {
|
|
89
|
+
if(!/^\d+$/.test(entry)) continue;
|
|
90
|
+
try {
|
|
91
|
+
const stat=fs.readFileSync(`/proc/${entry}/stat`,'utf8');
|
|
92
|
+
const fields=stat.slice(stat.lastIndexOf(')')+2).split(' ');
|
|
93
|
+
if(Number(fields[2])===groupId&&!['Z','X'].includes(fields[0])) return true;
|
|
94
|
+
} catch(error) { if(error.code!=='ENOENT'&&error.code!=='ESRCH') throw error; }
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
try { process.kill(-groupId,0); return true; }
|
|
99
|
+
catch(error) { if(error.code==='ESRCH') return false; throw error; }
|
|
100
|
+
};
|
|
101
|
+
while(groupHasExecutingProcess()) await new Promise(resolve=>setTimeout(resolve,10));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function add(args, flag, value) { if (value !== undefined && value !== null && value !== '') args.push(flag, String(value)); }
|
|
105
|
+
function addBool(args, flag, value) { if (value === true) args.push(flag); }
|
|
106
|
+
|
|
107
|
+
export function listArgs({ cwd, project, status, workspace_mode } = {}) {
|
|
108
|
+
const args = ['threads','list'];
|
|
109
|
+
add(args,'--cwd',cwd);
|
|
110
|
+
add(args,'--project',project);
|
|
111
|
+
add(args,'--status',status);
|
|
112
|
+
add(args,'--workspace-mode',workspace_mode);
|
|
113
|
+
return args;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function readArgs({ thread, detail, turns, max_chars, last_turn, first_turn } = {}) {
|
|
117
|
+
const args = ['threads','read','--thread',thread];
|
|
118
|
+
add(args,'--detail',detail);
|
|
119
|
+
add(args,'--turns',turns);
|
|
120
|
+
add(args,'--max-chars',max_chars);
|
|
121
|
+
addBool(args,'--last-turn',last_turn);
|
|
122
|
+
addBool(args,'--first-turn',first_turn);
|
|
123
|
+
return args;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function createArgs({ cwd, workspace_mode, project_policy, open, provider, model, speed_mode, thinking_effort, env_mode, permission, interaction_mode, options, wait, timeout, detail, max_chars } = {}) {
|
|
127
|
+
const args = ['threads','create','--stdin','--open',open ?? 'none'];
|
|
128
|
+
add(args,'--cwd',cwd);
|
|
129
|
+
add(args,'--workspace-mode',workspace_mode);
|
|
130
|
+
add(args,'--project-policy',project_policy);
|
|
131
|
+
add(args,'--provider',provider);
|
|
132
|
+
add(args,'--model',model);
|
|
133
|
+
add(args,'--speed-mode',speed_mode);
|
|
134
|
+
add(args,'--thinking-effort',thinking_effort);
|
|
135
|
+
add(args,'--env-mode',env_mode);
|
|
136
|
+
add(args,'--permission',permission);
|
|
137
|
+
add(args,'--interaction-mode',interaction_mode);
|
|
138
|
+
for (const option of options ?? []) add(args,'--option',option);
|
|
139
|
+
addBool(args,'--wait',wait);
|
|
140
|
+
add(args,'--timeout',timeout);
|
|
141
|
+
add(args,'--detail',detail);
|
|
142
|
+
add(args,'--max-chars',max_chars);
|
|
143
|
+
return args;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function threadSendArgs({ thread, if_busy, provider, model, speed_mode, thinking_effort, permission, interaction_mode, options, wake_settled, wait, timeout, detail, max_chars } = {}) {
|
|
147
|
+
const args = ['threads','send','--thread',thread,'--stdin'];
|
|
148
|
+
add(args,'--if-busy',if_busy);
|
|
149
|
+
add(args,'--provider',provider);
|
|
150
|
+
add(args,'--model',model);
|
|
151
|
+
add(args,'--speed-mode',speed_mode);
|
|
152
|
+
add(args,'--thinking-effort',thinking_effort);
|
|
153
|
+
add(args,'--permission',permission);
|
|
154
|
+
add(args,'--interaction-mode',interaction_mode);
|
|
155
|
+
for (const option of options ?? []) add(args,'--option',option);
|
|
156
|
+
addBool(args,'--wake-settled',wake_settled);
|
|
157
|
+
addBool(args,'--wait',wait);
|
|
158
|
+
add(args,'--timeout',timeout);
|
|
159
|
+
add(args,'--detail',detail);
|
|
160
|
+
add(args,'--max-chars',max_chars);
|
|
161
|
+
return args;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function waitArgs({ thread, timeout, detail, max_chars } = {}) {
|
|
165
|
+
const args = ['threads','wait','--thread',thread];
|
|
166
|
+
add(args,'--timeout',timeout);
|
|
167
|
+
add(args,'--detail',detail);
|
|
168
|
+
add(args,'--max-chars',max_chars);
|
|
169
|
+
return args;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Metadata requires a CLI supporting threads inspect. Never fall back to a
|
|
173
|
+
// transcript read: its truncation happens after fetching the whole history.
|
|
174
|
+
export async function inspectMetadata(threadId, invoke=callT3) {
|
|
175
|
+
try { return await invoke(['threads','inspect','--thread',threadId]); }
|
|
176
|
+
catch(error) { throw new Error('T3 metadata lookup requires supported threads inspect: '+safeDiagnostic(error.message,2000),{cause:error}); }
|
|
177
|
+
}
|
|
178
|
+
export async function inspectThread(threadId, environmentId) {
|
|
179
|
+
const data=await inspectMetadata(threadId);
|
|
180
|
+
if (!data?.thread || data.thread.id!==threadId || data.thread.deletedAt ||
|
|
181
|
+
!environmentId || !data.runtime?.environmentId || data.runtime.environmentId!==environmentId) return {state:'unavailable'};
|
|
182
|
+
return classifyThread(data.thread);
|
|
183
|
+
}
|
|
184
|
+
export function classifyThread(thread) {
|
|
185
|
+
if(thread.deletedAt) return {state:'deleted'};
|
|
186
|
+
if(thread.archivedAt) return {state:'archived'};
|
|
187
|
+
if(['stopped','cancelled','canceled','failed'].includes(thread.latestRun?.status)) return {state:'stopped'};
|
|
188
|
+
if(['stopped','settled','archived','deleted','cancelled','canceled'].includes(thread.status)) return {state:thread.status};
|
|
189
|
+
if(thread.status==='active') return {state:'active'};
|
|
190
|
+
return {state:'uncertain_lifecycle'};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Only a positive marker confirms delivery; an absent marker always leaves the outcome unproved.
|
|
194
|
+
export async function reconcileMarker(threadId, environmentId, eventId) {
|
|
195
|
+
if(!threadId||!environmentId||!eventId) return {state:'ambiguous',reason:'thread, environment or event binding unavailable'};
|
|
196
|
+
const data=await callT3(['threads','read','--thread',threadId,'--detail','messages']);
|
|
197
|
+
if (!data.thread || data.thread.id!==threadId || data.thread.deletedAt || !environmentId || data.runtime?.environmentId!==environmentId) return {state:'ambiguous',reason:'thread or environment changed'};
|
|
198
|
+
const messages=data.thread.messages;
|
|
199
|
+
if (!Array.isArray(messages)) return {state:'ambiguous',reason:'transcript messages unavailable'};
|
|
200
|
+
if (messages.some(message=>message.role==='user' && !message.textTruncated && typeof message.text==='string' && message.text.includes(marker(eventId)))) return {state:'confirmed'};
|
|
201
|
+
return {state:'ambiguous',reason:data.thread.view?.omittedTurns||messages.some(m=>m.textTruncated)?'transcript incomplete':'marker absent; send outcome unproved'};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export async function deliverT3(threadId, environmentId, eventId, message) {
|
|
205
|
+
const target=await inspectThread(threadId,environmentId);
|
|
206
|
+
if (target.state!=='active') return {state:'definite_failure',reason:`thread ${target.state}`};
|
|
207
|
+
try { await callT3(sendArgs(threadId),message); return {state:'confirmed'}; }
|
|
208
|
+
catch (error) { return {state:'ambiguous',reason:safeDiagnostic(error.message,2000)}; }
|
|
209
|
+
}
|