@50arms/platform-mcp 0.1.466 → 0.1.468
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compaction-control.js +6 -2
- package/dist/index.js +18 -7
- package/dist/job-key.js +15 -0
- package/dist/machine-daemon.js +3 -8
- package/dist/machine-toolkit.js +121 -208
- package/dist/session-host.js +178 -0
- package/dist/shutdown.js +6 -2
- package/package.json +1 -1
|
@@ -24,8 +24,12 @@
|
|
|
24
24
|
import { homedir } from "node:os";
|
|
25
25
|
import { prefixedLine } from "./one-line.js";
|
|
26
26
|
import { sessionControlDir, sessionControlFilePath, sessionControlFilesIn, } from "./session-control-file.js";
|
|
27
|
-
/**
|
|
28
|
-
|
|
27
|
+
/**
|
|
28
|
+
* The longest request line relayed whole. DX-6605: a compaction recommendation states what compacting would save (the context after it, its cost,
|
|
29
|
+
* the break-even calls, whose figures they are) and each handover proposal states the same for its sub-agent, so the longest request, the session's own recommendation
|
|
30
|
+
* with three proposals and default figures, is about 1,700 characters; a longer line would cut the ready call off its tail.
|
|
31
|
+
*/
|
|
32
|
+
export const COMPACTION_ASK_MAX_CODE_POINTS = 2000;
|
|
29
33
|
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
30
34
|
const isCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
31
35
|
const isTime = (v) => typeof v === "number" && Number.isFinite(v);
|
package/dist/index.js
CHANGED
|
@@ -81,6 +81,7 @@ import { READ_IDLE_TIMEOUT_MS } from "./listen.js";
|
|
|
81
81
|
import { REQUEST_TIMEOUT_MS, realScheduleInterval, realSleep, } from "./session-stream.js";
|
|
82
82
|
import { servePlanEventsWait } from "./plan-events-tool.js";
|
|
83
83
|
import { lookupRestartNotice, RESTART_NOTICE_ARGS } from "./restart-notice.js";
|
|
84
|
+
import { HOST_SESSION_ID_ENV, startSessionHostClaim, } from "./session-host.js";
|
|
84
85
|
import { makeSessionStop, stopWhenSessionEnds } from "./shutdown.js";
|
|
85
86
|
import { SUBAGENTS_LIVE_SUBCOMMAND, runSubagentsLiveCommand, } from "./subagents-live.js";
|
|
86
87
|
import { resolveBootCredential, } from "./credential.js";
|
|
@@ -88,7 +89,7 @@ import { SessionKeyUnusableError, deleteSessionKey } from "./session-key.js";
|
|
|
88
89
|
import { SessionAccess } from "./session-access.js";
|
|
89
90
|
import { PermissionRequests } from "./permission-request.js";
|
|
90
91
|
import { makeGuardedCalls } from "./guarded-calls.js";
|
|
91
|
-
import { JobKeyHolder } from "./job-key.js";
|
|
92
|
+
import { JobKeyHolder, sendWithJobKey } from "./job-key.js";
|
|
92
93
|
import { readOwnVersion } from "./version-floor.js";
|
|
93
94
|
import { createCheckoutDocsRootReporter, readCheckoutRepo, } from "./checkout-docs-root.js";
|
|
94
95
|
import { isPickupConnect, projectKeyOf, recordSessionConnectionAfterConnect, removeSessionConnectionAfterLeave, } from "./session-connection.js";
|
|
@@ -173,6 +174,8 @@ let toolAccessSync;
|
|
|
173
174
|
let permissionWatch;
|
|
174
175
|
// DX-4233 - late-bound with `access`; see `plan-events-relay.ts`. The plugin's relay loop (a person's session) and an orchestrator's waiter sub-agent (DX-4667) call `plan_events_wait` on it.
|
|
175
176
|
let planEventRelay;
|
|
177
|
+
// DX-7236 - the pointer file a command-line tool of this desktop session reads to learn which session id this server is; `null` for a server with no host id (a dispatch).
|
|
178
|
+
let sessionHostClaim;
|
|
176
179
|
/**
|
|
177
180
|
* Read the dispatch's default board from DANXBOT_BOARD_ID (the board's ref number the worker injects at the spawn site) and build the HTTP client.
|
|
178
181
|
* Unset (DX-4555) leaves the server board-less: a call that needs a board must then carry its own `board`
|
|
@@ -265,6 +268,13 @@ function boot() {
|
|
|
265
268
|
sync: () => toolAccessSync.sync(),
|
|
266
269
|
log: (line) => console.error(line),
|
|
267
270
|
});
|
|
271
|
+
sessionHostClaim = startSessionHostClaim({
|
|
272
|
+
hostSessionId: readEnvOptional(HOST_SESSION_ID_ENV),
|
|
273
|
+
sessionId: session?.id,
|
|
274
|
+
pid: process.pid,
|
|
275
|
+
scheduleInterval: realScheduleInterval,
|
|
276
|
+
log: (line) => console.error(line),
|
|
277
|
+
});
|
|
268
278
|
}
|
|
269
279
|
/**
|
|
270
280
|
* DX-4523 - this key's current permissions (`GET /api/auth/permissions`, DX-6369: the key list alone, where `/api/auth/me` composed a 27.6 KB payload that took seconds under load). A dashboard failure throws, a 401 or 403 included: a key the
|
|
@@ -661,14 +671,15 @@ renamedTool("50arms_api",
|
|
|
661
671
|
if (refused)
|
|
662
672
|
return haltResult(refused);
|
|
663
673
|
// DX-7098: while a system job's key is held the model's calls go out on it (never the take, never a hook's background call).
|
|
664
|
-
const
|
|
665
|
-
|
|
674
|
+
const guarded = await sendWithJobKey(jobKey, {
|
|
675
|
+
method: args.method,
|
|
676
|
+
path: args.path,
|
|
677
|
+
background: args.background,
|
|
666
678
|
gateOpen: isAgentGateOpenCall(args.method, args.path),
|
|
667
|
-
|
|
668
|
-
});
|
|
679
|
+
}, (bearer) => danxbotApi(client, args, {}, bearer), guardedCall);
|
|
669
680
|
if ("halt" in guarded)
|
|
670
681
|
return haltResult(guarded.halt);
|
|
671
|
-
const result =
|
|
682
|
+
const result = guarded.result;
|
|
672
683
|
const halt = termsHaltFor(result);
|
|
673
684
|
if (halt)
|
|
674
685
|
return haltResult(halt);
|
|
@@ -1226,7 +1237,7 @@ async function main() {
|
|
|
1226
1237
|
stdin: process.stdin,
|
|
1227
1238
|
signals: process,
|
|
1228
1239
|
exit: (code) => process.exit(code),
|
|
1229
|
-
stop: makeSessionStop(permissionWatch, planEventRelay),
|
|
1240
|
+
stop: makeSessionStop(permissionWatch, planEventRelay, sessionHostClaim),
|
|
1230
1241
|
});
|
|
1231
1242
|
const transport = new StdioServerTransport();
|
|
1232
1243
|
await server.connect(transport);
|
package/dist/job-key.js
CHANGED
|
@@ -43,5 +43,20 @@ export class JobKeyHolder {
|
|
|
43
43
|
return { ...result, body: { ...body, job_key: JOB_KEY_HELD_NOTE } };
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* One `50arms_api` call through the job-key holder (DX-7098): the bearer it goes out with (the job key while one is held), guarded like every
|
|
48
|
+
* tool's call, and the holder's answer rule applied to the result. `send` receives the bearer (`undefined` = the session's own key). The one
|
|
49
|
+
* wiring `index.ts` calls, so the tests drive the same code the tool does.
|
|
50
|
+
*/
|
|
51
|
+
export async function sendWithJobKey(holder, call, send, guard) {
|
|
52
|
+
const bearer = holder.bearerFor(call);
|
|
53
|
+
const guarded = await guard(() => send(bearer ?? undefined), {
|
|
54
|
+
gateOpen: call.gateOpen === true,
|
|
55
|
+
foreignKey: bearer !== null,
|
|
56
|
+
});
|
|
57
|
+
if ("halt" in guarded)
|
|
58
|
+
return guarded;
|
|
59
|
+
return { result: holder.afterCall(call, guarded.result, bearer !== null) };
|
|
60
|
+
}
|
|
46
61
|
const pathOf = (call) => call.path.split("?", 1)[0];
|
|
47
62
|
const isTake = (call) => call.method === "POST" && TAKE_PATH.test(call.path);
|
package/dist/machine-daemon.js
CHANGED
|
@@ -841,17 +841,13 @@ function createSystemLeftoverTracker(log, run = runCommand, platform = process.p
|
|
|
841
841
|
}
|
|
842
842
|
|
|
843
843
|
// src/machine-toolkit/contract.ts
|
|
844
|
-
var CONTRACT_VERSION =
|
|
844
|
+
var CONTRACT_VERSION = 3;
|
|
845
845
|
var REQUIRED_METRICS = [
|
|
846
846
|
"docker_data_disk_bytes",
|
|
847
|
-
"unowned_docker_resource_count",
|
|
848
847
|
"orphan_process_count"
|
|
849
848
|
];
|
|
850
849
|
var KERNEL_TOKEN_METRIC = "kernel_token_count";
|
|
851
|
-
var HEALTH_ITEM_LISTS = [
|
|
852
|
-
"unowned_docker_resources",
|
|
853
|
-
"orphan_processes"
|
|
854
|
-
];
|
|
850
|
+
var HEALTH_ITEM_LISTS = ["orphan_processes"];
|
|
855
851
|
var ContractViolation = class extends Error {
|
|
856
852
|
constructor(command, path, what) {
|
|
857
853
|
super(
|
|
@@ -981,9 +977,8 @@ var VALIDATORS = {
|
|
|
981
977
|
});
|
|
982
978
|
},
|
|
983
979
|
"label-check"(o, fail) {
|
|
984
|
-
exactKeys(o, "", [...ENVELOPE_KEYS, "
|
|
980
|
+
exactKeys(o, "", [...ENVELOPE_KEYS, "malformed"], fail);
|
|
985
981
|
checkEnvelope(o, fail);
|
|
986
|
-
checkItems(o.unowned, "unowned", ["reason"], fail);
|
|
987
982
|
checkItems(o.malformed, "malformed", ["reason"], fail);
|
|
988
983
|
}
|
|
989
984
|
};
|
package/dist/machine-toolkit.js
CHANGED
|
@@ -4,7 +4,7 @@ import { realpathSync } from "node:fs";
|
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
|
|
6
6
|
// src/machine-toolkit/contract.ts
|
|
7
|
-
var CONTRACT_VERSION =
|
|
7
|
+
var CONTRACT_VERSION = 3;
|
|
8
8
|
var EXIT = {
|
|
9
9
|
/** The command ran and everything it reports was read or done. */
|
|
10
10
|
ok: 0,
|
|
@@ -17,15 +17,11 @@ var EXIT = {
|
|
|
17
17
|
};
|
|
18
18
|
var REQUIRED_METRICS = [
|
|
19
19
|
"docker_data_disk_bytes",
|
|
20
|
-
"unowned_docker_resource_count",
|
|
21
20
|
"orphan_process_count"
|
|
22
21
|
];
|
|
23
22
|
var PROCESS_START_METRIC = "process_start_ms";
|
|
24
23
|
var KERNEL_TOKEN_METRIC = "kernel_token_count";
|
|
25
|
-
var HEALTH_ITEM_LISTS = [
|
|
26
|
-
"unowned_docker_resources",
|
|
27
|
-
"orphan_processes"
|
|
28
|
-
];
|
|
24
|
+
var HEALTH_ITEM_LISTS = ["orphan_processes"];
|
|
29
25
|
var ContractViolation = class extends Error {
|
|
30
26
|
constructor(command, path, what) {
|
|
31
27
|
super(
|
|
@@ -36,65 +32,65 @@ var ContractViolation = class extends Error {
|
|
|
36
32
|
};
|
|
37
33
|
var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
38
34
|
var join = (path, key) => path === "" ? key : `${path}.${key}`;
|
|
39
|
-
function objectAt(v, path,
|
|
40
|
-
if (!isObject(v)) return
|
|
35
|
+
function objectAt(v, path, fail) {
|
|
36
|
+
if (!isObject(v)) return fail(path, "must be an object");
|
|
41
37
|
return v;
|
|
42
38
|
}
|
|
43
|
-
function exactKeys(o, path, keys,
|
|
44
|
-
for (const k of keys) if (!(k in o))
|
|
39
|
+
function exactKeys(o, path, keys, fail) {
|
|
40
|
+
for (const k of keys) if (!(k in o)) fail(join(path, k), "is required");
|
|
45
41
|
for (const k of Object.keys(o))
|
|
46
|
-
if (!keys.includes(k))
|
|
42
|
+
if (!keys.includes(k)) fail(join(path, k), "is not part of the contract");
|
|
47
43
|
}
|
|
48
|
-
function stringAt(o, key, path,
|
|
44
|
+
function stringAt(o, key, path, fail) {
|
|
49
45
|
const v = o[key];
|
|
50
46
|
if (typeof v !== "string" || v === "")
|
|
51
|
-
return
|
|
47
|
+
return fail(join(path, key), "must be a non-empty string");
|
|
52
48
|
return v;
|
|
53
49
|
}
|
|
54
|
-
function listAt(v, path,
|
|
55
|
-
if (!Array.isArray(v)) return
|
|
50
|
+
function listAt(v, path, fail) {
|
|
51
|
+
if (!Array.isArray(v)) return fail(path, "must be a list");
|
|
56
52
|
return v;
|
|
57
53
|
}
|
|
58
|
-
function checkItem(v, path, extra,
|
|
59
|
-
const o = objectAt(v, path,
|
|
60
|
-
exactKeys(o, path, ["id", "detail", ...extra],
|
|
61
|
-
stringAt(o, "id", path,
|
|
54
|
+
function checkItem(v, path, extra, fail) {
|
|
55
|
+
const o = objectAt(v, path, fail);
|
|
56
|
+
exactKeys(o, path, ["id", "detail", ...extra], fail);
|
|
57
|
+
stringAt(o, "id", path, fail);
|
|
62
58
|
if (typeof o.detail !== "string")
|
|
63
|
-
|
|
64
|
-
for (const k of extra) stringAt(o, k, path,
|
|
59
|
+
fail(join(path, "detail"), "must be a string");
|
|
60
|
+
for (const k of extra) stringAt(o, k, path, fail);
|
|
65
61
|
}
|
|
66
|
-
function checkItems(v, path, extra,
|
|
67
|
-
listAt(v, path,
|
|
68
|
-
(item, i) => checkItem(item, `${path}[${i}]`, extra,
|
|
62
|
+
function checkItems(v, path, extra, fail) {
|
|
63
|
+
listAt(v, path, fail).forEach(
|
|
64
|
+
(item, i) => checkItem(item, `${path}[${i}]`, extra, fail)
|
|
69
65
|
);
|
|
70
66
|
}
|
|
71
|
-
function checkMetric(v, path,
|
|
72
|
-
const o = objectAt(v, path,
|
|
73
|
-
exactKeys(o, path, ["value", "reason", "source", "age_seconds"],
|
|
67
|
+
function checkMetric(v, path, fail) {
|
|
68
|
+
const o = objectAt(v, path, fail);
|
|
69
|
+
exactKeys(o, path, ["value", "reason", "source", "age_seconds"], fail);
|
|
74
70
|
if (o.value === null) {
|
|
75
71
|
if (typeof o.reason !== "string" || o.reason === "")
|
|
76
|
-
|
|
72
|
+
fail(`${path}.reason`, "must say why the value is null");
|
|
77
73
|
} else {
|
|
78
74
|
if (typeof o.value !== "number" || !Number.isFinite(o.value) || o.value < 0)
|
|
79
|
-
|
|
75
|
+
fail(`${path}.value`, "must be null or a finite number of at least 0");
|
|
80
76
|
if (o.reason !== null)
|
|
81
|
-
|
|
77
|
+
fail(`${path}.reason`, "must be null when the value was read");
|
|
82
78
|
}
|
|
83
79
|
if (o.source !== "fresh" && o.source !== "cached")
|
|
84
|
-
|
|
80
|
+
fail(`${path}.source`, "must be 'fresh' or 'cached'");
|
|
85
81
|
if (typeof o.age_seconds !== "number" || !Number.isFinite(o.age_seconds) || o.age_seconds < 0)
|
|
86
|
-
|
|
82
|
+
fail(`${path}.age_seconds`, "must be a number of at least 0");
|
|
87
83
|
if (o.source === "fresh" && o.age_seconds !== 0)
|
|
88
|
-
|
|
84
|
+
fail(`${path}.age_seconds`, "must be 0 for a fresh reading");
|
|
89
85
|
}
|
|
90
|
-
function checkEnvelope(o,
|
|
86
|
+
function checkEnvelope(o, fail) {
|
|
91
87
|
if (o.contract_version !== CONTRACT_VERSION)
|
|
92
|
-
|
|
93
|
-
stringAt(o, "toolkit_version", "",
|
|
94
|
-
stringAt(o, "profile", "",
|
|
95
|
-
const at = stringAt(o, "measured_at", "",
|
|
88
|
+
fail("contract_version", `must be ${CONTRACT_VERSION}`);
|
|
89
|
+
stringAt(o, "toolkit_version", "", fail);
|
|
90
|
+
stringAt(o, "profile", "", fail);
|
|
91
|
+
const at = stringAt(o, "measured_at", "", fail);
|
|
96
92
|
if (Number.isNaN(new Date(at).getTime()))
|
|
97
|
-
|
|
93
|
+
fail("measured_at", "must be an ISO time");
|
|
98
94
|
}
|
|
99
95
|
var ENVELOPE_KEYS = [
|
|
100
96
|
"contract_version",
|
|
@@ -103,73 +99,72 @@ var ENVELOPE_KEYS = [
|
|
|
103
99
|
"measured_at"
|
|
104
100
|
];
|
|
105
101
|
var VALIDATORS = {
|
|
106
|
-
health(o,
|
|
107
|
-
exactKeys(o, "", [...ENVELOPE_KEYS, "metrics", "items"],
|
|
108
|
-
checkEnvelope(o,
|
|
109
|
-
const metrics = objectAt(o.metrics, "metrics",
|
|
102
|
+
health(o, fail) {
|
|
103
|
+
exactKeys(o, "", [...ENVELOPE_KEYS, "metrics", "items"], fail);
|
|
104
|
+
checkEnvelope(o, fail);
|
|
105
|
+
const metrics = objectAt(o.metrics, "metrics", fail);
|
|
110
106
|
for (const name of REQUIRED_METRICS)
|
|
111
|
-
if (!(name in metrics))
|
|
107
|
+
if (!(name in metrics)) fail(`metrics.${name}`, "is required");
|
|
112
108
|
for (const [name, metric] of Object.entries(metrics))
|
|
113
|
-
checkMetric(metric, `metrics.${name}`,
|
|
109
|
+
checkMetric(metric, `metrics.${name}`, fail);
|
|
114
110
|
const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
|
|
115
111
|
if (typeof tokens === "number" && !Number.isInteger(tokens))
|
|
116
|
-
|
|
117
|
-
const items = objectAt(o.items, "items",
|
|
118
|
-
exactKeys(items, "items", HEALTH_ITEM_LISTS,
|
|
112
|
+
fail(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
|
|
113
|
+
const items = objectAt(o.items, "items", fail);
|
|
114
|
+
exactKeys(items, "items", HEALTH_ITEM_LISTS, fail);
|
|
119
115
|
for (const list of HEALTH_ITEM_LISTS)
|
|
120
|
-
checkItems(items[list], `items.${list}`, [],
|
|
116
|
+
checkItems(items[list], `items.${list}`, [], fail);
|
|
121
117
|
},
|
|
122
|
-
sweep(o,
|
|
123
|
-
exactKeys(o, "", [...ENVELOPE_KEYS, "dry_run", "kinds"],
|
|
124
|
-
checkEnvelope(o,
|
|
118
|
+
sweep(o, fail) {
|
|
119
|
+
exactKeys(o, "", [...ENVELOPE_KEYS, "dry_run", "kinds"], fail);
|
|
120
|
+
checkEnvelope(o, fail);
|
|
125
121
|
if (typeof o.dry_run !== "boolean")
|
|
126
|
-
|
|
127
|
-
listAt(o.kinds, "kinds",
|
|
122
|
+
fail("dry_run", "must be true or false");
|
|
123
|
+
listAt(o.kinds, "kinds", fail).forEach((k, i) => {
|
|
128
124
|
const path = `kinds[${i}]`;
|
|
129
|
-
const kind = objectAt(k, path,
|
|
125
|
+
const kind = objectAt(k, path, fail);
|
|
130
126
|
exactKeys(
|
|
131
127
|
kind,
|
|
132
128
|
path,
|
|
133
129
|
["kind", "removed", "kept", "failed", "flagged"],
|
|
134
|
-
|
|
130
|
+
fail
|
|
135
131
|
);
|
|
136
|
-
stringAt(kind, "kind", path,
|
|
137
|
-
checkItems(kind.removed, `${path}.removed`, [],
|
|
138
|
-
checkItems(kind.kept, `${path}.kept`, ["reason"],
|
|
139
|
-
checkItems(kind.failed, `${path}.failed`, ["error"],
|
|
140
|
-
checkItems(kind.flagged, `${path}.flagged`, ["reason"],
|
|
132
|
+
stringAt(kind, "kind", path, fail);
|
|
133
|
+
checkItems(kind.removed, `${path}.removed`, [], fail);
|
|
134
|
+
checkItems(kind.kept, `${path}.kept`, ["reason"], fail);
|
|
135
|
+
checkItems(kind.failed, `${path}.failed`, ["error"], fail);
|
|
136
|
+
checkItems(kind.flagged, `${path}.flagged`, ["reason"], fail);
|
|
141
137
|
});
|
|
142
138
|
},
|
|
143
|
-
maintain(o,
|
|
144
|
-
exactKeys(o, "", [...ENVELOPE_KEYS, "steps"],
|
|
145
|
-
checkEnvelope(o,
|
|
146
|
-
listAt(o.steps, "steps",
|
|
139
|
+
maintain(o, fail) {
|
|
140
|
+
exactKeys(o, "", [...ENVELOPE_KEYS, "steps"], fail);
|
|
141
|
+
checkEnvelope(o, fail);
|
|
142
|
+
listAt(o.steps, "steps", fail).forEach((s, i) => {
|
|
147
143
|
const path = `steps[${i}]`;
|
|
148
|
-
const step = objectAt(s, path,
|
|
149
|
-
exactKeys(step, path, ["name", "status", "detail"],
|
|
150
|
-
stringAt(step, "name", path,
|
|
144
|
+
const step = objectAt(s, path, fail);
|
|
145
|
+
exactKeys(step, path, ["name", "status", "detail"], fail);
|
|
146
|
+
stringAt(step, "name", path, fail);
|
|
151
147
|
if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed")
|
|
152
|
-
|
|
148
|
+
fail(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
|
|
153
149
|
if (typeof step.detail !== "string")
|
|
154
|
-
|
|
150
|
+
fail(join(path, "detail"), "must be a string");
|
|
155
151
|
});
|
|
156
152
|
},
|
|
157
|
-
"label-check"(o,
|
|
158
|
-
exactKeys(o, "", [...ENVELOPE_KEYS, "
|
|
159
|
-
checkEnvelope(o,
|
|
160
|
-
checkItems(o.
|
|
161
|
-
checkItems(o.malformed, "malformed", ["reason"], fail2);
|
|
153
|
+
"label-check"(o, fail) {
|
|
154
|
+
exactKeys(o, "", [...ENVELOPE_KEYS, "malformed"], fail);
|
|
155
|
+
checkEnvelope(o, fail);
|
|
156
|
+
checkItems(o.malformed, "malformed", ["reason"], fail);
|
|
162
157
|
}
|
|
163
158
|
};
|
|
164
159
|
function assertContract(command, report) {
|
|
165
|
-
const
|
|
160
|
+
const fail = (path, what) => {
|
|
166
161
|
throw new ContractViolation(
|
|
167
162
|
command,
|
|
168
163
|
path === "" ? "(document)" : path,
|
|
169
164
|
what
|
|
170
165
|
);
|
|
171
166
|
};
|
|
172
|
-
VALIDATORS[command](objectAt(report, "",
|
|
167
|
+
VALIDATORS[command](objectAt(report, "", fail), fail);
|
|
173
168
|
}
|
|
174
169
|
var metricRead = (value, source = "fresh", ageSeconds = 0) => ({ value, reason: null, source, age_seconds: ageSeconds });
|
|
175
170
|
var metricUnread = (reason) => ({
|
|
@@ -207,107 +202,6 @@ function readDockerDataDisk(localAppData = process.env.LOCALAPPDATA, stat = stat
|
|
|
207
202
|
}
|
|
208
203
|
}
|
|
209
204
|
|
|
210
|
-
// src/machine-toolkit/docker-flags.mjs
|
|
211
|
-
import { readFileSync } from "node:fs";
|
|
212
|
-
import { join as join4 } from "node:path";
|
|
213
|
-
|
|
214
|
-
// src/machine-toolkit/machine-home.mjs
|
|
215
|
-
import { execFileSync } from "node:child_process";
|
|
216
|
-
import { existsSync } from "node:fs";
|
|
217
|
-
import { homedir, release } from "node:os";
|
|
218
|
-
import { join as join3 } from "node:path";
|
|
219
|
-
function isWsl(kernelRelease = release(), platform = process.platform, hasDrvFs = existsSync("/mnt/c/Users")) {
|
|
220
|
-
return platform === "linux" && /microsoft/i.test(kernelRelease) && hasDrvFs;
|
|
221
|
-
}
|
|
222
|
-
var WSL_CALL_TIMEOUT_MS = 1e4;
|
|
223
|
-
function windowsHomeFromWsl() {
|
|
224
|
-
const raw = execFileSync("cmd.exe", ["/c", "echo %USERPROFILE%"], {
|
|
225
|
-
windowsHide: true,
|
|
226
|
-
encoding: "utf8",
|
|
227
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
228
|
-
timeout: WSL_CALL_TIMEOUT_MS
|
|
229
|
-
}).replace(/\r/g, "").trim();
|
|
230
|
-
if (raw === "" || raw.includes("%"))
|
|
231
|
-
throw new Error(
|
|
232
|
-
`could not resolve the Windows home from cmd.exe (it said '${raw}')`
|
|
233
|
-
);
|
|
234
|
-
const path = execFileSync("wslpath", ["-u", raw], {
|
|
235
|
-
windowsHide: true,
|
|
236
|
-
encoding: "utf8",
|
|
237
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
238
|
-
timeout: WSL_CALL_TIMEOUT_MS
|
|
239
|
-
}).trim();
|
|
240
|
-
if (!existsSync(path))
|
|
241
|
-
throw new Error(
|
|
242
|
-
`the Windows home '${raw}' is not a directory under /mnt/c`
|
|
243
|
-
);
|
|
244
|
-
return path;
|
|
245
|
-
}
|
|
246
|
-
var COMPACTION_WINDOW_FILE = "compaction-window";
|
|
247
|
-
function compactionWindowOpen(home = machineHome()) {
|
|
248
|
-
return existsSync(join3(home, ".danxbot", COMPACTION_WINDOW_FILE));
|
|
249
|
-
}
|
|
250
|
-
function machineHome() {
|
|
251
|
-
return isWsl() ? windowsHomeFromWsl() : homedir();
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// src/machine-toolkit/docker-flags.mjs
|
|
255
|
-
var FLAGS_STALE_MS = 3 * 60 * 60 * 1e3;
|
|
256
|
-
var UNOWNED_REASON_PREFIX = "UNOWNED: ";
|
|
257
|
-
function flagsFile(home = machineHome()) {
|
|
258
|
-
return join4(home, ".danxbot", "docker-flags.json");
|
|
259
|
-
}
|
|
260
|
-
function fail(path, what) {
|
|
261
|
-
throw Object.assign(new Error(`${path} is malformed: ${what}`), {
|
|
262
|
-
code: "EMALFORMED"
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
function validateFlags(value, path) {
|
|
266
|
-
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
267
|
-
fail(path, "not a JSON object");
|
|
268
|
-
if (typeof value.at !== "string" || Number.isNaN(new Date(value.at).getTime()))
|
|
269
|
-
fail(path, `"at" must be an ISO time, not ${JSON.stringify(value.at)}`);
|
|
270
|
-
if (!Number.isInteger(value.unowned) || value.unowned < 0)
|
|
271
|
-
fail(
|
|
272
|
-
path,
|
|
273
|
-
`"unowned" must be a whole number, not ${JSON.stringify(value.unowned)}`
|
|
274
|
-
);
|
|
275
|
-
if (!Array.isArray(value.flagged)) fail(path, `"flagged" must be a list`);
|
|
276
|
-
for (const f of value.flagged) {
|
|
277
|
-
if (f === null || typeof f !== "object" || typeof f.id !== "string" || typeof f.reason !== "string" || !(f.card === null || typeof f.card === "string")) {
|
|
278
|
-
fail(
|
|
279
|
-
path,
|
|
280
|
-
`every "flagged" entry needs a string id and reason and a card (string or null), not ${JSON.stringify(f)}`
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return {
|
|
285
|
-
at: value.at,
|
|
286
|
-
unowned: value.unowned,
|
|
287
|
-
flagged: value.flagged.map((f) => ({
|
|
288
|
-
id: f.id,
|
|
289
|
-
reason: f.reason,
|
|
290
|
-
card: f.card
|
|
291
|
-
}))
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
function readFlags(path = flagsFile()) {
|
|
295
|
-
let text;
|
|
296
|
-
try {
|
|
297
|
-
text = readFileSync(path, "utf8");
|
|
298
|
-
} catch (err) {
|
|
299
|
-
if (err.code === "ENOENT") return null;
|
|
300
|
-
throw err;
|
|
301
|
-
}
|
|
302
|
-
let value;
|
|
303
|
-
try {
|
|
304
|
-
value = JSON.parse(text);
|
|
305
|
-
} catch (err) {
|
|
306
|
-
fail(path, `not JSON (${err.message})`);
|
|
307
|
-
}
|
|
308
|
-
return validateFlags(value, path);
|
|
309
|
-
}
|
|
310
|
-
|
|
311
205
|
// src/machine-toolkit/deadline.ts
|
|
312
206
|
var realScheduler = (fire, ms) => {
|
|
313
207
|
const timer = setTimeout(fire, ms);
|
|
@@ -350,9 +244,49 @@ function errMessage(err) {
|
|
|
350
244
|
// src/machine-toolkit/probe.ts
|
|
351
245
|
import { createHash } from "node:crypto";
|
|
352
246
|
import { existsSync as existsSync2, mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
353
|
-
import { join as
|
|
247
|
+
import { join as join4 } from "node:path";
|
|
354
248
|
import { performance } from "node:perf_hooks";
|
|
355
249
|
|
|
250
|
+
// src/machine-toolkit/machine-home.mjs
|
|
251
|
+
import { execFileSync } from "node:child_process";
|
|
252
|
+
import { existsSync } from "node:fs";
|
|
253
|
+
import { homedir, release } from "node:os";
|
|
254
|
+
import { join as join3 } from "node:path";
|
|
255
|
+
function isWsl(kernelRelease = release(), platform = process.platform, hasDrvFs = existsSync("/mnt/c/Users")) {
|
|
256
|
+
return platform === "linux" && /microsoft/i.test(kernelRelease) && hasDrvFs;
|
|
257
|
+
}
|
|
258
|
+
var WSL_CALL_TIMEOUT_MS = 1e4;
|
|
259
|
+
function windowsHomeFromWsl() {
|
|
260
|
+
const raw = execFileSync("cmd.exe", ["/c", "echo %USERPROFILE%"], {
|
|
261
|
+
windowsHide: true,
|
|
262
|
+
encoding: "utf8",
|
|
263
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
264
|
+
timeout: WSL_CALL_TIMEOUT_MS
|
|
265
|
+
}).replace(/\r/g, "").trim();
|
|
266
|
+
if (raw === "" || raw.includes("%"))
|
|
267
|
+
throw new Error(
|
|
268
|
+
`could not resolve the Windows home from cmd.exe (it said '${raw}')`
|
|
269
|
+
);
|
|
270
|
+
const path = execFileSync("wslpath", ["-u", raw], {
|
|
271
|
+
windowsHide: true,
|
|
272
|
+
encoding: "utf8",
|
|
273
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
274
|
+
timeout: WSL_CALL_TIMEOUT_MS
|
|
275
|
+
}).trim();
|
|
276
|
+
if (!existsSync(path))
|
|
277
|
+
throw new Error(
|
|
278
|
+
`the Windows home '${raw}' is not a directory under /mnt/c`
|
|
279
|
+
);
|
|
280
|
+
return path;
|
|
281
|
+
}
|
|
282
|
+
var COMPACTION_WINDOW_FILE = "compaction-window";
|
|
283
|
+
function compactionWindowOpen(home = machineHome()) {
|
|
284
|
+
return existsSync(join3(home, ".danxbot", COMPACTION_WINDOW_FILE));
|
|
285
|
+
}
|
|
286
|
+
function machineHome() {
|
|
287
|
+
return isWsl() ? windowsHomeFromWsl() : homedir();
|
|
288
|
+
}
|
|
289
|
+
|
|
356
290
|
// src/machine-toolkit/processes.ts
|
|
357
291
|
import { execFile } from "node:child_process";
|
|
358
292
|
var ORPHAN_MIN_AGE_MS = 10 * 60 * 1e3;
|
|
@@ -600,7 +534,7 @@ public static class DxTokeProbe {
|
|
|
600
534
|
`;
|
|
601
535
|
var TOKEN_COMPILE_TIMEOUT_MS = 15e3;
|
|
602
536
|
function cscPath(windir) {
|
|
603
|
-
return
|
|
537
|
+
return join4(
|
|
604
538
|
windir ?? String.raw`C:\Windows`,
|
|
605
539
|
"Microsoft.NET",
|
|
606
540
|
"Framework64",
|
|
@@ -619,12 +553,12 @@ var realTokenProbeFiles = {
|
|
|
619
553
|
};
|
|
620
554
|
async function ensureTokenProbeExe(opts) {
|
|
621
555
|
const files = opts.files ?? realTokenProbeFiles;
|
|
622
|
-
const exe =
|
|
556
|
+
const exe = join4(opts.dir, tokenProbeExeName());
|
|
623
557
|
if (files.exists(exe)) return exe;
|
|
624
558
|
files.mkdir(opts.dir);
|
|
625
559
|
const tag = String(opts.pid ?? process.pid);
|
|
626
560
|
const source = exe.replace(/\.exe$/, ".cs");
|
|
627
|
-
const temp =
|
|
561
|
+
const temp = join4(opts.dir, `token-probe-${tag}.tmp.exe`);
|
|
628
562
|
files.write(source, TOKEN_PROBE_SOURCE);
|
|
629
563
|
await opts.run(
|
|
630
564
|
cscPath(opts.windir),
|
|
@@ -654,7 +588,7 @@ async function readKernelTokenCount(opts = {}) {
|
|
|
654
588
|
return { kind: "unsupported", reason: TOKEN_COUNT_UNSUPPORTED };
|
|
655
589
|
const run = opts.run ?? runCommand;
|
|
656
590
|
const exe = await ensureTokenProbeExe({
|
|
657
|
-
dir: opts.dir ??
|
|
591
|
+
dir: opts.dir ?? join4(machineHome(), ".danxbot"),
|
|
658
592
|
run,
|
|
659
593
|
files: opts.files,
|
|
660
594
|
windir: opts.windir ?? process.env.WINDIR,
|
|
@@ -669,16 +603,16 @@ async function readKernelTokenCount(opts = {}) {
|
|
|
669
603
|
}
|
|
670
604
|
|
|
671
605
|
// src/machine-toolkit/toolkit.ts
|
|
672
|
-
import { readFileSync
|
|
606
|
+
import { readFileSync } from "node:fs";
|
|
673
607
|
var PROFILE = "windows-wsl-docker";
|
|
674
608
|
function resolveToolkitVersion(stamped, readManifest) {
|
|
675
609
|
return stamped ?? readManifest();
|
|
676
610
|
}
|
|
677
611
|
var readOwnManifest = () => JSON.parse(
|
|
678
|
-
|
|
612
|
+
readFileSync(new URL("../../package.json", import.meta.url), "utf8")
|
|
679
613
|
).version;
|
|
680
614
|
var TOOLKIT_VERSION = resolveToolkitVersion(
|
|
681
|
-
false ? void 0 : "0.1.
|
|
615
|
+
false ? void 0 : "0.1.468",
|
|
682
616
|
readOwnManifest
|
|
683
617
|
);
|
|
684
618
|
function envelope(now) {
|
|
@@ -740,29 +674,11 @@ async function collectHealth(src, opts = {}) {
|
|
|
740
674
|
}),
|
|
741
675
|
"timing a process start"
|
|
742
676
|
);
|
|
743
|
-
const [dataDisk,
|
|
677
|
+
const [dataDisk, orphans, tokens] = await Promise.all([
|
|
744
678
|
read(() => {
|
|
745
679
|
const disk = src.dataDisk();
|
|
746
680
|
return disk.bytes === null ? unread(disk.unavailableReason) : { metric: metricRead(disk.bytes), items: [] };
|
|
747
681
|
}, "reading docker_data.vhdx"),
|
|
748
|
-
read(() => {
|
|
749
|
-
const flags = src.flags();
|
|
750
|
-
if (flags === null)
|
|
751
|
-
return unread(
|
|
752
|
-
"no real Docker sweep has written docker-flags.json on this machine yet"
|
|
753
|
-
);
|
|
754
|
-
const ageMs = Math.max(0, now.getTime() - new Date(flags.at).getTime());
|
|
755
|
-
if (ageMs > FLAGS_STALE_MS)
|
|
756
|
-
return unread(
|
|
757
|
-
`the last Docker sweep result is ${(ageMs / 36e5).toFixed(1)} h old (older than ${FLAGS_STALE_MS / 36e5} h): the hourly sweep has stopped, so its count is stale`
|
|
758
|
-
);
|
|
759
|
-
const ageSeconds = Math.round(ageMs / 1e3);
|
|
760
|
-
const items = flags.flagged.filter((f) => f.reason.startsWith(UNOWNED_REASON_PREFIX)).map((f) => ({
|
|
761
|
-
id: f.id,
|
|
762
|
-
detail: f.reason.slice(UNOWNED_REASON_PREFIX.length)
|
|
763
|
-
}));
|
|
764
|
-
return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
|
|
765
|
-
}, "reading the Docker flags file"),
|
|
766
682
|
read(async () => {
|
|
767
683
|
if (src.compactionWindowOpen())
|
|
768
684
|
return unread(
|
|
@@ -798,13 +714,11 @@ async function collectHealth(src, opts = {}) {
|
|
|
798
714
|
...envelope(now),
|
|
799
715
|
metrics: {
|
|
800
716
|
docker_data_disk_bytes: dataDisk.metric,
|
|
801
|
-
unowned_docker_resource_count: unowned.metric,
|
|
802
717
|
orphan_process_count: orphans.metric,
|
|
803
718
|
[PROCESS_START_METRIC]: processStart.metric,
|
|
804
719
|
[KERNEL_TOKEN_METRIC]: tokens.metric
|
|
805
720
|
},
|
|
806
721
|
items: {
|
|
807
|
-
unowned_docker_resources: unowned.items,
|
|
808
722
|
orphan_processes: orphans.items
|
|
809
723
|
}
|
|
810
724
|
};
|
|
@@ -835,7 +749,6 @@ function collectFromThisMachine() {
|
|
|
835
749
|
return collectHealth({
|
|
836
750
|
now: () => /* @__PURE__ */ new Date(),
|
|
837
751
|
dataDisk: () => readDockerDataDisk(),
|
|
838
|
-
flags: () => readFlags(),
|
|
839
752
|
orphans: (now, signal) => reportOrphanProcesses(now, void 0, void 0, signal, "when-running"),
|
|
840
753
|
compactionWindowOpen: () => compactionWindowOpen(),
|
|
841
754
|
processStartMs: (signal) => probeProcessStart({ spawnFn: spawn, signal }),
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DX-7236 (DEC-846) - which session id a desktop session's command-line tools act as, after a clear.
|
|
3
|
+
*
|
|
4
|
+
* A clear gives every process the session starts afterwards a new `CLAUDE_CODE_SESSION_ID`, but a clear that keeps the Claude process keeps its MCP server running, still
|
|
5
|
+
* holding the old id, the key the person approved for it and the `assigned_agent` the cards carry. The server therefore stays the session's identity, and the CLI (`make land`
|
|
6
|
+
* among them) only has to learn which id that is. `CLAUDE_CODE_HOST_SESSION_ID` is the desktop app's own id for the session row: every process of one desktop session inherits it
|
|
7
|
+
* and it survives a clear, so the server writes a pointer file keyed by it and the CLI reads it.
|
|
8
|
+
*
|
|
9
|
+
* `~/.config/danxbot/session-hosts/<host session id>.json` holds `{schema_version, sessionId, pid}`: the session id of the MCP server serving that desktop session, and that server's pid.
|
|
10
|
+
* No key moves between session ids (PBLM-3624): the key stays bound to the id it was approved for.
|
|
11
|
+
*
|
|
12
|
+
* Owner rule: a LIVE owner wins. A `claude` started inside a session (a `claude -p` from a Bash call) inherits the parent's host id while the parent is alive, and its server must never take the
|
|
13
|
+
* parent's pointer. A server re-claims on its own interval, because in a clear that replaces the Claude process the new server can boot while the old one is still in its shutdown settle: its boot
|
|
14
|
+
* claim stands aside, and only a later claim, once the old one has exited, takes the pointer over.
|
|
15
|
+
*
|
|
16
|
+
* Known limit: a pointer whose owner died without cleaning up, and whose pid the OS reuses before the next server's claim, reads as live. The window is the seconds between the old server's death and
|
|
17
|
+
* the new one's re-claim; accepted, not designed out.
|
|
18
|
+
*
|
|
19
|
+
* This module imports nothing but `node:` and the session-id segment check, so a CLI that loads it runs in a plain shell.
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
22
|
+
import { homedir } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
import { writeFileDurable } from "./durable-write.js";
|
|
25
|
+
import { assertSessionIdSegment } from "./session-connection.js";
|
|
26
|
+
/** One canonical shape (CLAUDE.md Core Principle 1): a file of any other version is refused. */
|
|
27
|
+
export const SESSION_HOST_SCHEMA_VERSION = 1;
|
|
28
|
+
/** The desktop app's own id for the session row; survives a clear and is inherited by every process of the session. A terminal host does not set it. */
|
|
29
|
+
export const HOST_SESSION_ID_ENV = "CLAUDE_CODE_HOST_SESSION_ID";
|
|
30
|
+
/** How often a server repeats its claim. */
|
|
31
|
+
export const SESSION_HOST_CLAIM_INTERVAL_MS = 15_000;
|
|
32
|
+
export function sessionHostDir(home = homedir()) {
|
|
33
|
+
return join(home, ".config", "danxbot", "session-hosts");
|
|
34
|
+
}
|
|
35
|
+
export function sessionHostPath(hostSessionId, home = homedir()) {
|
|
36
|
+
assertSessionIdSegment(hostSessionId);
|
|
37
|
+
return join(sessionHostDir(home), `${hostSessionId}.json`);
|
|
38
|
+
}
|
|
39
|
+
/** A pointer file that is there but unreadable or of another shape: named by path, never skipped. */
|
|
40
|
+
export class SessionHostUnusableError extends Error {
|
|
41
|
+
path;
|
|
42
|
+
constructor(path, why) {
|
|
43
|
+
super(`the session host pointer ${path} is unusable: ${why}`);
|
|
44
|
+
this.path = path;
|
|
45
|
+
this.name = "SessionHostUnusableError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** Whether `pid` names a running process. `EPERM` means it exists and belongs to someone else, so it is alive. */
|
|
49
|
+
export function isPidAlive(pid) {
|
|
50
|
+
try {
|
|
51
|
+
process.kill(pid, 0);
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
return err.code === "EPERM";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function invalidReason(value) {
|
|
59
|
+
if (typeof value !== "object" || value === null)
|
|
60
|
+
return "it is not an object";
|
|
61
|
+
const r = value;
|
|
62
|
+
if (r.schema_version !== SESSION_HOST_SCHEMA_VERSION) {
|
|
63
|
+
return `schema_version is ${JSON.stringify(r.schema_version)}, not ${SESSION_HOST_SCHEMA_VERSION}`;
|
|
64
|
+
}
|
|
65
|
+
if (typeof r.sessionId !== "string" || r.sessionId === "")
|
|
66
|
+
return "sessionId is not a non-empty string";
|
|
67
|
+
if (!Number.isInteger(r.pid) || r.pid <= 0)
|
|
68
|
+
return "pid is not a positive integer";
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/** The pointer in `path`, or `null` when there is none. Any other trouble throws `SessionHostUnusableError`. */
|
|
72
|
+
export function readSessionHost(path) {
|
|
73
|
+
let raw;
|
|
74
|
+
try {
|
|
75
|
+
raw = readFileSync(path, "utf-8");
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
if (err.code === "ENOENT")
|
|
79
|
+
return null;
|
|
80
|
+
throw new SessionHostUnusableError(path, err.message);
|
|
81
|
+
}
|
|
82
|
+
let parsed;
|
|
83
|
+
try {
|
|
84
|
+
parsed = JSON.parse(raw);
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
throw new SessionHostUnusableError(path, `not JSON (${err.message})`);
|
|
88
|
+
}
|
|
89
|
+
const invalid = invalidReason(parsed);
|
|
90
|
+
if (invalid !== null)
|
|
91
|
+
throw new SessionHostUnusableError(path, invalid);
|
|
92
|
+
return parsed;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Take the pointer for this server's desktop session: write it unless the file already names a different pid that is still alive. An absent file and a dead owner are taken over. A file that is there but
|
|
96
|
+
* unusable throws (`SessionHostUnusableError`).
|
|
97
|
+
*/
|
|
98
|
+
export function claimSessionHost(identity) {
|
|
99
|
+
const { hostSessionId, sessionId, pid, home } = identity;
|
|
100
|
+
const isAlive = identity.isAlive ?? isPidAlive;
|
|
101
|
+
const path = sessionHostPath(hostSessionId, home);
|
|
102
|
+
const current = readSessionHost(path);
|
|
103
|
+
if (current !== null) {
|
|
104
|
+
if (current.pid === pid && current.sessionId === sessionId)
|
|
105
|
+
return "held";
|
|
106
|
+
if (current.pid !== pid && isAlive(current.pid))
|
|
107
|
+
return "owned-by-other";
|
|
108
|
+
}
|
|
109
|
+
const record = {
|
|
110
|
+
schema_version: SESSION_HOST_SCHEMA_VERSION,
|
|
111
|
+
sessionId,
|
|
112
|
+
pid,
|
|
113
|
+
};
|
|
114
|
+
writeFileDurable(path, JSON.stringify(record));
|
|
115
|
+
return "claimed";
|
|
116
|
+
}
|
|
117
|
+
/** Delete the pointer, only when it still names this server's pid: another server may have taken it over. An absent file is nothing to do. */
|
|
118
|
+
export function releaseSessionHost(identity) {
|
|
119
|
+
const path = sessionHostPath(identity.hostSessionId, identity.home);
|
|
120
|
+
const current = readSessionHost(path);
|
|
121
|
+
if (current !== null && current.pid === identity.pid)
|
|
122
|
+
rmSync(path, { force: true });
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The server's claim: take the pointer now (a failure throws, so a pointer this code cannot read stops the boot), then repeat on `scheduleInterval` every `SESSION_HOST_CLAIM_INTERVAL_MS`. `null` for a
|
|
126
|
+
* server with no host id or no session id (a dispatch server): it writes nothing. A failing re-claim is logged and tried again on the next tick, since a throw from a timer would end the server.
|
|
127
|
+
*/
|
|
128
|
+
export function startSessionHostClaim(input) {
|
|
129
|
+
const { hostSessionId, sessionId, pid, home, isAlive, log } = input;
|
|
130
|
+
if (hostSessionId === undefined || sessionId === undefined)
|
|
131
|
+
return null;
|
|
132
|
+
const identity = {
|
|
133
|
+
hostSessionId,
|
|
134
|
+
sessionId,
|
|
135
|
+
pid,
|
|
136
|
+
home,
|
|
137
|
+
isAlive,
|
|
138
|
+
};
|
|
139
|
+
claimSessionHost(identity);
|
|
140
|
+
const timer = input.scheduleInterval(() => {
|
|
141
|
+
try {
|
|
142
|
+
claimSessionHost(identity);
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
log(`[platform-mcp] could not re-claim the session host pointer: ${err.message}`);
|
|
146
|
+
}
|
|
147
|
+
}, SESSION_HOST_CLAIM_INTERVAL_MS);
|
|
148
|
+
let stopped = false;
|
|
149
|
+
return {
|
|
150
|
+
stop: () => {
|
|
151
|
+
if (stopped)
|
|
152
|
+
return;
|
|
153
|
+
stopped = true;
|
|
154
|
+
timer.stop();
|
|
155
|
+
releaseSessionHost(identity);
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The session id a command-line tool acts as, or `null` for none. In order:
|
|
161
|
+
* 1. `CLAUDE_CODE_SESSION_ID` unset or empty: none, whatever the host id says. Dropping the session id is how a detached run that outlives its session (`start-pass`, `finish-card-now`, DX-5809) is told to use the machine
|
|
162
|
+
* credential instead of the session's key, which can be revoked once the session ends. Those runs still inherit the host id, so reading the pointer first would hand them that key.
|
|
163
|
+
* 2. the pointer's `sessionId`, when `CLAUDE_CODE_HOST_SESSION_ID` is set and its pointer names a live pid: the live MCP server's id, the one the key and the cards' `assigned_agent` are bound to.
|
|
164
|
+
* 3. the process's own `CLAUDE_CODE_SESSION_ID`: with no live server for this host id, the process's own id is the live session's id (a clear that replaces the process gives the new server and the new shells the same new id).
|
|
165
|
+
* A pointer that is there but unusable throws, naming its path.
|
|
166
|
+
*/
|
|
167
|
+
export function resolveSessionId(env, home, isAlive = isPidAlive) {
|
|
168
|
+
const own = env.CLAUDE_CODE_SESSION_ID;
|
|
169
|
+
if (own === undefined || own === "")
|
|
170
|
+
return null;
|
|
171
|
+
const hostSessionId = env[HOST_SESSION_ID_ENV];
|
|
172
|
+
if (hostSessionId !== undefined && hostSessionId !== "") {
|
|
173
|
+
const pointer = readSessionHost(sessionHostPath(hostSessionId, home));
|
|
174
|
+
if (pointer !== null && isAlive(pointer.pid))
|
|
175
|
+
return pointer.sessionId;
|
|
176
|
+
}
|
|
177
|
+
return own;
|
|
178
|
+
}
|
package/dist/shutdown.js
CHANGED
|
@@ -31,10 +31,14 @@ export function stopWhenSessionEnds(wiring) {
|
|
|
31
31
|
/**
|
|
32
32
|
* DX-5415: the server's stop callback, the one link from every shutdown trigger to the relay's settle: it returns the relay's
|
|
33
33
|
* pending `close()` so a signal handler can wait for it before exiting.
|
|
34
|
+
* DX-7236: it also stops the server's session host claim (`session-host.ts`): the re-claim interval ends and the pointer file is deleted when it still names this server.
|
|
34
35
|
*/
|
|
35
|
-
export function makeSessionStop(permissionWatch, planEventRelay) {
|
|
36
|
+
export function makeSessionStop(permissionWatch, planEventRelay, sessionHostClaim) {
|
|
36
37
|
return () => {
|
|
37
38
|
permissionWatch.stop();
|
|
38
|
-
|
|
39
|
+
// DX-7236: starts the relay's settle first, so a pointer file this server cannot read (its release throws) never costs the held finals.
|
|
40
|
+
const closing = planEventRelay.close();
|
|
41
|
+
sessionHostClaim?.stop();
|
|
42
|
+
return closing;
|
|
39
43
|
};
|
|
40
44
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@50arms/platform-mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.468",
|
|
4
4
|
"description": "Stdio MCP server fronting the 50 Arms dashboard API for agents (operator sessions and dispatched workers alike): the generic 50arms_api/50arms_api_list/50arms_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (session_connect, request_permission, attach_file, and 50arms_slack_reply) (DX-3465, PLN-11 R-25).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|