@clagentic/console 1.10.0-beta.1 → 1.10.0-beta.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.
Files changed (68) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/agent-dispatch-tool.js +20 -0
  4. package/lib/build-changes.js +79 -0
  5. package/lib/build-identity.js +192 -0
  6. package/lib/build-monitor.js +125 -0
  7. package/lib/build-sha.json +2 -2
  8. package/lib/build-update-offer.js +141 -0
  9. package/lib/build-update-restart.js +142 -0
  10. package/lib/build-update-standing.js +184 -0
  11. package/lib/cli/daemon-launch.js +8 -5
  12. package/lib/cli/ipc-subcommands.js +6 -0
  13. package/lib/cli/session-subcommands.js +122 -0
  14. package/lib/cli-sessions.js +8 -1
  15. package/lib/codex-defaults.js +8 -2
  16. package/lib/daemon-projects.js +19 -0
  17. package/lib/daemon.js +166 -127
  18. package/lib/memory-shed.js +13 -32
  19. package/lib/project-connection.js +14 -0
  20. package/lib/project-external-trigger.js +91 -123
  21. package/lib/project-loop.js +5 -4
  22. package/lib/project-prompt-responses.js +5 -4
  23. package/lib/project-sessions.js +43 -68
  24. package/lib/project-user-message.js +7 -20
  25. package/lib/project.js +23 -5
  26. package/lib/prompt-registry.js +7 -0
  27. package/lib/public/css/diagnostics.css +30 -0
  28. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  29. package/lib/public/modules/app-messages.js +7 -2
  30. package/lib/public/modules/app-panels.js +0 -1
  31. package/lib/public/modules/build-update-detail.js +54 -0
  32. package/lib/public/modules/diagnostics.js +126 -20
  33. package/lib/public/modules/tools.js +14 -2
  34. package/lib/public/modules/vendor-picker.js +2 -2
  35. package/lib/public/modules/vendor-registry.js +11 -2
  36. package/lib/sdk-bridge.js +62 -15
  37. package/lib/sdk-message-processor.js +11 -20
  38. package/lib/sdk-skill-discovery.js +65 -60
  39. package/lib/server.js +15 -2
  40. package/lib/session-id.js +33 -0
  41. package/lib/session-input-ipc.js +32 -0
  42. package/lib/session-input.js +379 -0
  43. package/lib/session-reclaim.js +284 -0
  44. package/lib/session-resume.js +172 -0
  45. package/lib/sessions.js +16 -2
  46. package/lib/supervisor.js +39 -0
  47. package/lib/turn-initiator.js +108 -0
  48. package/lib/vendor-registry-message.js +1 -0
  49. package/lib/ws-schema.js +3 -1
  50. package/lib/yoke/adapters/claude-vendor.js +0 -1
  51. package/lib/yoke/adapters/claude-worker.js +6 -4
  52. package/lib/yoke/adapters/claude.js +34 -34
  53. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  54. package/lib/yoke/adapters/codex-vendor.js +15 -15
  55. package/lib/yoke/adapters/codex.js +121 -61
  56. package/lib/yoke/auth-checks.js +8 -21
  57. package/lib/yoke/codex-app-server.js +27 -71
  58. package/lib/yoke/codex-binary.js +254 -0
  59. package/lib/yoke/codex-command.js +122 -0
  60. package/lib/yoke/codex-protocol.js +96 -0
  61. package/lib/yoke/codex-version.js +135 -0
  62. package/lib/yoke/index.js +20 -4
  63. package/lib/yoke/install-probe.js +21 -6
  64. package/lib/yoke/interface.js +11 -5
  65. package/lib/yoke/registry.js +41 -4
  66. package/package.json +1 -2
  67. package/scripts/verify-installed-build.js +59 -17
  68. package/lib/lore-attestation.js +0 -73
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ // build-update-restart.js — the only path from "a newer build is installed" to
4
+ // "the daemon restarts", and it starts only from an operator's confirmed click.
5
+ //
6
+ // Two steps, both initiated by the operator over the admin WebSocket:
7
+ // 1. request() with no token answers with the offer: both builds, the commits
8
+ // between them, and the live sessions and background agents a restart now
9
+ // would end. It restarts nothing.
10
+ // 2. request(token) with the token from that offer. The restart is scheduled
11
+ // only when the offer is still true: the installed build is the one
12
+ // offered, and nothing is live now that the operator was not shown. If
13
+ // anything changed, a fresh offer is returned instead and the operator
14
+ // confirms again.
15
+ // A running turn is given a bounded time to finish; when the restart finally
16
+ // fires, it re-checks the same condition and cancels if a session started
17
+ // after the operator confirmed.
18
+
19
+ var crypto = require('crypto');
20
+
21
+ var { collectInterruptions, coveredBy, buildOffer } = require('./build-update-offer');
22
+
23
+ var OFFER_TTL_MS = 10 * 60 * 1000;
24
+ var MAX_OUTSTANDING_OFFERS = 20;
25
+
26
+ /**
27
+ * @param {object} o
28
+ * @param {function(): object} o.assess — fresh assessBuild() result
29
+ * @param {function(): Array<{slug: string, sm: object}>} o.getProjects
30
+ * @param {function(object): Promise<object>} o.listChanges — ({fromSha, toSha}) -> changes
31
+ * @param {function(): void} o.restart — performs the restart; called only after confirmation
32
+ * @param {function(function, object): void} o.waitForIdleThenAct — build-update-check's
33
+ * @param {function(string): void} o.announce — tells every client why a confirmed restart was cancelled
34
+ * @param {function(string): void} [o.log]
35
+ * @param {number} [o.waitMs] — how long running turns get to finish
36
+ * @param {function(): number} [o.nowMs]
37
+ */
38
+ function createBuildUpdateRestart(o) {
39
+ var log = typeof o.log === 'function' ? o.log : function () {};
40
+ var now = typeof o.nowMs === 'function' ? o.nowMs : Date.now;
41
+ var waitMs = o.waitMs > 0 ? o.waitMs : 60 * 1000;
42
+ var offers = new Map(); // token -> { keys, installedKey, expires }
43
+ var restarting = false;
44
+
45
+ function installedKeyOf(a) { return a.installedBuildSha + ':' + a.installedContentHash; }
46
+
47
+ function prune() {
48
+ var t = now();
49
+ offers.forEach(function (v, token) { if (v.expires <= t) offers.delete(token); });
50
+ while (offers.size >= MAX_OUTSTANDING_OFFERS) offers.delete(offers.keys().next().value);
51
+ }
52
+
53
+ async function issueOffer(assessment, note) {
54
+ var changes;
55
+ try {
56
+ changes = await o.listChanges({ fromSha: assessment.loadedBuildSha, toSha: assessment.installedBuildSha });
57
+ } catch (e) {
58
+ changes = { available: false, commits: [], truncated: false, reason: 'the change list failed' };
59
+ log('Could not list changes for the build-update offer: ' + (e && e.message ? e.message : e));
60
+ }
61
+ // Reading the change list takes time. The offer reflects the build and the
62
+ // live sessions as they are now, not as they were when it was asked for.
63
+ var fresh = o.assess();
64
+ if (fresh.state !== 'stale' || installedKeyOf(fresh) !== installedKeyOf(assessment)) {
65
+ return { status: 'not_stale', assessment: fresh };
66
+ }
67
+ var interruptions = collectInterruptions(o.getProjects());
68
+ prune();
69
+ var token = crypto.randomBytes(16).toString('hex');
70
+ offers.set(token, {
71
+ keys: interruptions.keys.slice(),
72
+ installedKey: installedKeyOf(assessment),
73
+ expires: now() + OFFER_TTL_MS,
74
+ });
75
+ var offer = buildOffer({
76
+ assessment: assessment,
77
+ changes: changes,
78
+ interruptions: interruptions,
79
+ waitSeconds: Math.round(waitMs / 1000),
80
+ token: token,
81
+ });
82
+ return { status: 'confirm', offer: offer, note: note || null };
83
+ }
84
+
85
+ function stillCovered(offered, assessment) {
86
+ var a = assessment;
87
+ return a.state === 'stale' && installedKeyOf(a) === offered.installedKey
88
+ && coveredBy(collectInterruptions(o.getProjects()).keys, offered.keys);
89
+ }
90
+
91
+ /**
92
+ * @param {?string} token — the token of an offer the operator was shown
93
+ * @returns {Promise<{status: string, offer?: object, note?: string}>}
94
+ * status: 'not_stale' | 'confirm' | 'restarting'
95
+ */
96
+ async function request(token) {
97
+ var assessment = o.assess();
98
+ if (assessment.state !== 'stale') {
99
+ return { status: 'not_stale', assessment: assessment };
100
+ }
101
+
102
+ if (!token) return issueOffer(assessment, null);
103
+
104
+ var offered = offers.get(token);
105
+ offers.delete(token); // one confirmation per offer
106
+ if (!offered || offered.expires <= now()) {
107
+ return issueOffer(assessment, 'That offer expired. Review the current one.');
108
+ }
109
+ if (!stillCovered(offered, assessment)) {
110
+ return issueOffer(assessment,
111
+ 'Something changed since you opened the offer (a build or a live session). Review the current one.');
112
+ }
113
+ if (restarting) return { status: 'restarting' };
114
+ restarting = true;
115
+ log('Operator confirmed restart to adopt build ' + assessment.installedBuildSha +
116
+ '; waiting up to ' + Math.round(waitMs / 1000) + 's for running turns');
117
+
118
+ o.waitForIdleThenAct({
119
+ getActiveCount: function () {
120
+ var i = collectInterruptions(o.getProjects());
121
+ return i.processingCount + i.agentCount;
122
+ },
123
+ timeoutMs: waitMs,
124
+ onIdle: function () {
125
+ var fresh = o.assess();
126
+ if (!stillCovered(offered, fresh)) {
127
+ restarting = false;
128
+ log('Confirmed restart cancelled: the installed build or the live sessions changed after confirmation');
129
+ o.announce('The restart you confirmed was cancelled because the installed build or the live ' +
130
+ 'sessions changed while it waited. Nothing was restarted. Open the update offer again to review it.');
131
+ return;
132
+ }
133
+ o.restart();
134
+ },
135
+ });
136
+ return { status: 'restarting', waitSeconds: Math.round(waitMs / 1000) };
137
+ }
138
+
139
+ return { request: request };
140
+ }
141
+
142
+ module.exports = { createBuildUpdateRestart: createBuildUpdateRestart, OFFER_TTL_MS: OFFER_TTL_MS };
@@ -0,0 +1,184 @@
1
+ 'use strict';
2
+
3
+ // build-update-standing.js — the one standing "newer build installed" offer.
4
+ //
5
+ // The offer is level-triggered. After every build poll the daemon calls
6
+ // reconcile() with the DESIRED state (the confirmed stale assessment, or null),
7
+ // and this module changes only the difference between that and what clients
8
+ // were last shown: show, refresh in place, or retract. Calling it again with the
9
+ // same input changes nothing and broadcasts nothing. There are no announce and
10
+ // retract events for another module to keep in step with.
11
+ //
12
+ // While the build is genuinely stale an actionable offer is always visible: it
13
+ // is shown at once, with its change list marked unavailable, and refreshed in
14
+ // place when a read succeeds. A slow, failed or throwing read never removes or
15
+ // withholds the restart action.
16
+ //
17
+ // It broadcasts; it never restarts anything (that is
18
+ // lib/build-update-restart.js, on a confirmed click).
19
+
20
+ var SOURCE = 'build-update';
21
+
22
+ var READING = 'the change list is still being read';
23
+ var FAILED_REASON = 'the change list could not be read';
24
+
25
+ // What the change list looks like to a client, ordered by what can change it.
26
+ var PENDING = 'pending';
27
+ var LISTED = 'listed';
28
+ var FAILED = 'failed';
29
+
30
+ function unavailable(reason) {
31
+ return { available: false, commits: [], truncated: false, reason: reason };
32
+ }
33
+
34
+ function offerKeyOf(a) {
35
+ return a.loadedBuildSha + ':' + a.installedBuildSha + ':' + a.installedContentHash;
36
+ }
37
+
38
+ // The change list depends only on the two builds, not on the content hash.
39
+ function readKeyOf(a) {
40
+ return a.loadedBuildSha + ':' + a.installedBuildSha;
41
+ }
42
+
43
+ /**
44
+ * @param {object} o
45
+ * @param {function(object): Promise<object>} o.listChanges — ({fromSha, toSha}) -> changes
46
+ * @param {function(object, object): object} o.compose — (assessment, changes) -> diagnostic message
47
+ * @param {function(object): void} o.broadcast — sends a message to every connected client
48
+ * @param {function(): ?object} o.desired — the CURRENT desired assessment (confirmed stale) or null
49
+ * @param {number} [o.retryAfterMs] — minimum time between retries of a failed read
50
+ * @param {function(): number} [o.now]
51
+ * @param {function(string): void} [o.log]
52
+ */
53
+ function createStandingOffer(o) {
54
+ var log = typeof o.log === 'function' ? o.log : function () {};
55
+ var now = typeof o.now === 'function' ? o.now : Date.now;
56
+ var retryAfterMs = o.retryAfterMs >= 0 ? o.retryAfterMs : 30 * 60 * 1000;
57
+
58
+ // What clients were last shown: {offerKey, changeListStatus, message}, set only
59
+ // after the broadcast succeeded.
60
+ var shown = null;
61
+ // readKey -> {status, changes, reason, failedAt, inFlight}
62
+ var reads = {};
63
+
64
+ function describe(e) { return e && e.message ? e.message : String(e); }
65
+
66
+ function readChanges(a) {
67
+ // A synchronous throw from the reader is a failed read like a rejection.
68
+ try {
69
+ return Promise.resolve(o.listChanges({ fromSha: a.loadedBuildSha, toSha: a.installedBuildSha }));
70
+ } catch (e) {
71
+ return Promise.reject(e);
72
+ }
73
+ }
74
+
75
+ function startRead(a, key) {
76
+ var entry = reads[key] || { status: PENDING, changes: null, reason: null, failedAt: 0, inFlight: false };
77
+ reads[key] = entry;
78
+ entry.inFlight = true;
79
+ readChanges(a).then(function (changes) {
80
+ entry.inFlight = false;
81
+ entry.status = LISTED;
82
+ entry.changes = changes;
83
+ }, function (err) {
84
+ entry.inFlight = false;
85
+ // A list already read stays; otherwise the failure and its reason are cached.
86
+ if (entry.status !== LISTED) {
87
+ entry.status = FAILED;
88
+ entry.reason = FAILED_REASON;
89
+ }
90
+ entry.failedAt = now();
91
+ // The detail stays in the journal; clients get only the reason class.
92
+ log('Could not read the changes for the build-update offer: ' + describe(err));
93
+ }).then(function () {
94
+ // Always against the LATEST desired state, never the one this read started
95
+ // under, so an obsolete result cannot restore an offer.
96
+ var latest;
97
+ try {
98
+ latest = o.desired();
99
+ } catch (e) {
100
+ log('Could not read the current build assessment: ' + describe(e));
101
+ return;
102
+ }
103
+ reconcile(latest);
104
+ });
105
+ }
106
+
107
+ function changesFor(entry) {
108
+ if (entry.status === LISTED) return entry.changes;
109
+ if (entry.status === FAILED) return unavailable(entry.reason);
110
+ return unavailable(READING);
111
+ }
112
+
113
+ function retract() {
114
+ o.broadcast({ type: 'diagnostic_retract', source: SOURCE });
115
+ shown = null;
116
+ }
117
+
118
+ function prune(keepKey) {
119
+ Object.keys(reads).forEach(function (k) {
120
+ if (k !== keepKey && !reads[k].inFlight) delete reads[k];
121
+ });
122
+ }
123
+
124
+ function reconcileUnsafe(desired) {
125
+ if (!desired) {
126
+ if (shown !== null) retract();
127
+ prune(null);
128
+ return;
129
+ }
130
+ var offerKey = offerKeyOf(desired);
131
+ var readKey = readKeyOf(desired);
132
+ var entry = reads[readKey];
133
+ if (!entry) {
134
+ startRead(desired, readKey);
135
+ entry = reads[readKey];
136
+ } else if (!entry.inFlight && entry.status === FAILED && now() - entry.failedAt >= retryAfterMs) {
137
+ startRead(desired, readKey);
138
+ }
139
+
140
+ var summary = { offerKey: offerKey, changeListStatus: entry.status };
141
+ if (shown !== null && shown.offerKey === summary.offerKey && shown.changeListStatus === summary.changeListStatus) {
142
+ prune(readKey);
143
+ return;
144
+ }
145
+
146
+ var message = o.compose(desired, changesFor(entry));
147
+ // A different build replaces the offer; the same build is refreshed in place
148
+ // (never retracted first, so the restart action does not flicker).
149
+ var refresh = shown !== null && shown.offerKey === summary.offerKey;
150
+ if (shown !== null && !refresh) retract();
151
+ // The stored copy, replayed to a client that connects later, is a plain
152
+ // diagnostic; `refresh` tells a client already holding the entry to update it
153
+ // and not to bring back one the operator dismissed.
154
+ o.broadcast(refresh ? Object.assign({}, message, { refresh: true }) : message);
155
+ shown = { offerKey: summary.offerKey, changeListStatus: summary.changeListStatus, message: message };
156
+ prune(readKey);
157
+ }
158
+
159
+ /**
160
+ * Bring what clients see in line with `desired`. Idempotent; never throws:
161
+ * the poll loop that calls it must survive a compose or broadcast failure,
162
+ * and the next poll retries because nothing is recorded as shown until the
163
+ * broadcast has succeeded.
164
+ */
165
+ function reconcile(desired) {
166
+ try {
167
+ reconcileUnsafe(desired);
168
+ } catch (e) {
169
+ log('Could not reconcile the build-update offer: ' + describe(e));
170
+ }
171
+ }
172
+
173
+ return {
174
+ reconcile: reconcile,
175
+ /** What a client that connects now should be shown, or null when no offer stands. */
176
+ current: function () { return shown === null ? null : shown.message; },
177
+ /** The state to send a client on connect: the held offer, or an explicit "no offer". */
178
+ forNewClient: function () {
179
+ return shown === null ? { type: 'diagnostic_retract', source: SOURCE } : shown.message;
180
+ },
181
+ };
182
+ }
183
+
184
+ module.exports = { createStandingOffer: createStandingOffer, SOURCE: SOURCE };
@@ -22,6 +22,9 @@ var {
22
22
  loadClayrc, readCrashInfo, CONFIG_DIR, CLAGENTIC_HOME,
23
23
  } = require("../config");
24
24
  var { sendIPCCommand } = require("../ipc");
25
+ // A daemon this CLI starts is not a service manager's main process, whatever
26
+ // environment the CLI itself was run from.
27
+ var { unsupervisedEnv } = require("../supervisor");
25
28
  var { hasAdmin, getSetupCode, hashPin } = require("../users");
26
29
  var { log, sym, a } = require("./tui");
27
30
  var { getLocalIP, ensureCerts, isPortFree } = require("./net-detect");
@@ -205,7 +208,7 @@ async function restartDaemonFromConfig(opts) {
205
208
  detached: true,
206
209
  windowsHide: true,
207
210
  stdio: ["ignore", logFd, logFd],
208
- env: Object.assign({}, process.env, {
211
+ env: Object.assign(unsupervisedEnv(), {
209
212
  CLAGENTIC_CONSOLE_CONFIG: configPath(),
210
213
  CLAGENTIC_CONSOLE_HOME: CLAGENTIC_HOME,
211
214
  }),
@@ -386,7 +389,7 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers, c
386
389
  detached: true,
387
390
  windowsHide: true,
388
391
  stdio: ["ignore", logFd, logFd],
389
- env: Object.assign({}, process.env, {
392
+ env: Object.assign(unsupervisedEnv(), {
390
393
  CLAGENTIC_CONSOLE_CONFIG: configPath(),
391
394
  CLAGENTIC_CONSOLE_HOME: CLAGENTIC_HOME,
392
395
  }),
@@ -569,7 +572,7 @@ async function devMode(mode, keepAwake, existingPinHash, wantOsUsers, cliOpts) {
569
572
  function spawnDaemon() {
570
573
  child = spawn(process.execPath, [daemonScript], {
571
574
  stdio: ["ignore", "inherit", "inherit"],
572
- env: Object.assign({}, process.env, {
575
+ env: Object.assign(unsupervisedEnv(), {
573
576
  CLAGENTIC_CONSOLE_CONFIG: configPath(),
574
577
  CLAGENTIC_CONSOLE_HOME: CLAGENTIC_HOME,
575
578
  }),
@@ -734,7 +737,7 @@ async function _restartDaemonWithTLS(config, callback, cliOpts) {
734
737
  detached: true,
735
738
  windowsHide: true,
736
739
  stdio: ["ignore", logFd, logFd],
737
- env: Object.assign({}, process.env, {
740
+ env: Object.assign(unsupervisedEnv(), {
738
741
  CLAGENTIC_CONSOLE_CONFIG: configPath(),
739
742
  CLAGENTIC_CONSOLE_HOME: CLAGENTIC_HOME,
740
743
  }),
@@ -761,7 +764,7 @@ async function _restartDaemonWithTLS(config, callback, cliOpts) {
761
764
  detached: true,
762
765
  windowsHide: true,
763
766
  stdio: ["ignore", logFd2, logFd2],
764
- env: Object.assign({}, process.env, {
767
+ env: Object.assign(unsupervisedEnv(), {
765
768
  CLAGENTIC_CONSOLE_CONFIG: configPath(),
766
769
  CLAGENTIC_CONSOLE_HOME: CLAGENTIC_HOME,
767
770
  }),
@@ -217,6 +217,12 @@ function handleProcessBuildStatus() {
217
217
  // formatted output).
218
218
  console.log(JSON.stringify({
219
219
  loadedBuildSha: res.loadedBuildSha,
220
+ installedBuildSha: res.installedBuildSha,
221
+ state: res.state,
222
+ reason: res.reason,
223
+ detail: res.detail,
224
+ loadedContentHash: res.loadedContentHash,
225
+ installedContentHash: res.installedContentHash,
220
226
  staleInodes: res.staleInodes,
221
227
  pid: res.pid,
222
228
  }, null, 2));
@@ -0,0 +1,122 @@
1
+ // lib/cli/session-subcommands.js
2
+ //
3
+ // `clagentic-console open-session` and `clagentic-console send-input`: open a
4
+ // session in a project, or send input to one, through the running daemon's IPC
5
+ // socket. Both print the daemon's result as JSON on stdout and exit 0 when the
6
+ // request was acted on (opened, delivered, resumed-and-delivered), 1 otherwise
7
+ // (not-found, refused, error), so a script can branch on either.
8
+
9
+ var fs = require("fs");
10
+
11
+ var { loadConfig, socketPath, isDaemonAliveAsync } = require("../config");
12
+ var { sendIPCCommand } = require("../ipc");
13
+
14
+ // A resumed session starts a runtime before the call answers: longer than the
15
+ // IPC default.
16
+ var IPC_TIMEOUT_MS = 30000;
17
+
18
+ var FLAGS = {
19
+ "--project": "projectSlug",
20
+ "--session": "sessionId",
21
+ "--prompt": "prompt",
22
+ "--vendor": "vendor",
23
+ "--agent": "agentName",
24
+ "--visibility": "sessionVisibility",
25
+ "--initiator": "initiator",
26
+ "--context-note": "contextNote",
27
+ };
28
+
29
+ var USAGE = {
30
+ "open-session": "Usage: clagentic-console open-session --project <slug> --prompt <text|-> [--vendor <id>] [--agent <name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>]",
31
+ "send-input": "Usage: clagentic-console send-input --project <slug> --session <id> --prompt <text|-> [--initiator <kind>] [--context-note <text>]",
32
+ };
33
+
34
+ var ALLOWED = {
35
+ "open-session": ["projectSlug", "prompt", "vendor", "agentName", "sessionVisibility", "initiator", "contextNote"],
36
+ "send-input": ["projectSlug", "sessionId", "prompt", "initiator", "contextNote"],
37
+ };
38
+
39
+ var REQUIRED = {
40
+ "open-session": ["projectSlug", "prompt"],
41
+ "send-input": ["projectSlug", "sessionId", "prompt"],
42
+ };
43
+
44
+ var IPC_COMMAND = {
45
+ "open-session": "open_session",
46
+ "send-input": "send_session_input",
47
+ };
48
+
49
+ // Parses the arguments after the verb. Returns { request } or { error }.
50
+ // Pure: reading a "-" prompt from stdin is the handler's job.
51
+ function parseSessionArgs(verb, args) {
52
+ var allowed = ALLOWED[verb];
53
+ var request = {};
54
+ for (var i = 0; i < args.length; i++) {
55
+ var key = Object.prototype.hasOwnProperty.call(FLAGS, args[i]) ? FLAGS[args[i]] : null;
56
+ if (!key || allowed.indexOf(key) === -1) return { error: "Unknown option for " + verb + ": " + args[i] };
57
+ if (i + 1 >= args.length) return { error: "Missing value for " + args[i] };
58
+ request[key] = args[++i];
59
+ }
60
+ var required = REQUIRED[verb];
61
+ for (var r = 0; r < required.length; r++) {
62
+ if (!request[required[r]]) {
63
+ var flag = Object.keys(FLAGS).filter(function (f) { return FLAGS[f] === required[r]; })[0];
64
+ return { error: "Missing required option " + flag };
65
+ }
66
+ }
67
+ return { request: request };
68
+ }
69
+
70
+ // The IPC layer reports its own failures (timeout, refused connection) as
71
+ // { ok: false, error }; give them the same result shape as the daemon's.
72
+ function normalizeResponse(res) {
73
+ if (res && typeof res === "object" && res.result) return res;
74
+ var reason = res && res.error ? String(res.error) : "unexpected response from the daemon";
75
+ return { ok: false, result: "error", reason: reason };
76
+ }
77
+
78
+ function fail(message) {
79
+ console.error(message);
80
+ process.exit(1);
81
+ }
82
+
83
+ function runSessionVerb(verb, args) {
84
+ var parsed = parseSessionArgs(verb, args);
85
+ if (parsed.error) {
86
+ console.error(parsed.error);
87
+ fail(USAGE[verb]);
88
+ return;
89
+ }
90
+ var request = parsed.request;
91
+ if (request.prompt === "-") {
92
+ request.prompt = fs.readFileSync(0, "utf8").replace(/\n$/, "");
93
+ }
94
+ request.cmd = IPC_COMMAND[verb];
95
+
96
+ requestDaemon(request).then(function (res) {
97
+ console.log(JSON.stringify(res, null, 2));
98
+ // Not process.exit: on a pipe it can cut the JSON off before stdout drains.
99
+ process.exitCode = res && res.ok ? 0 : 1;
100
+ });
101
+ }
102
+
103
+ // Always resolves to a result object: an IPC failure of any kind (a rejected
104
+ // promise included) becomes { ok: false, result: "error" }. deps is for tests.
105
+ function requestDaemon(request, deps) {
106
+ deps = deps || {};
107
+ var isAlive = deps.isDaemonAlive || function () { return isDaemonAliveAsync(loadConfig()); };
108
+ var send = deps.sendIPC || function (req) { return sendIPCCommand(socketPath(), req, IPC_TIMEOUT_MS); };
109
+ return Promise.resolve().then(isAlive).then(function (alive) {
110
+ if (!alive) return { ok: false, result: "error", reason: "no running daemon" };
111
+ return send(request).then(normalizeResponse);
112
+ }).catch(function (err) {
113
+ return { ok: false, result: "error", reason: "daemon request failed: " + (err && err.message ? err.message : String(err)) };
114
+ });
115
+ }
116
+
117
+ module.exports = {
118
+ requestDaemon: requestDaemon,
119
+ parseSessionArgs: parseSessionArgs,
120
+ runSessionVerb: runSessionVerb,
121
+ SESSION_VERBS: Object.keys(IPC_COMMAND),
122
+ };
@@ -3,6 +3,7 @@ var path = require("path");
3
3
  var readline = require("readline");
4
4
  var utils = require("./utils");
5
5
  var { REAL_HOME } = require("./config");
6
+ var { sessionPathWithin } = require("./session-id");
6
7
 
7
8
  var encodeCwd = utils.encodeCwd;
8
9
 
@@ -220,7 +221,13 @@ function extractText(content) {
220
221
  */
221
222
  function readCliSessionHistory(cwd, sessionId) {
222
223
  var encoded = encodeCwd(cwd);
223
- var filePath = path.join(REAL_HOME, ".claude", "projects", encoded, sessionId + ".jsonl");
224
+ var filePath;
225
+ try {
226
+ filePath = sessionPathWithin(path.join(REAL_HOME, ".claude", "projects", encoded), sessionId, ".jsonl");
227
+ } catch (e) {
228
+ // An id that is not a plain file name has no history to read.
229
+ return Promise.resolve([]);
230
+ }
224
231
 
225
232
  return new Promise(function (resolve) {
226
233
  var history = [];
@@ -1,15 +1,21 @@
1
+ var normalizeApprovalPolicy = require("./yoke/codex-protocol").normalizeApprovalPolicy;
2
+
1
3
  // lr-f7a4 — sandbox defaults to "workspace-write" (matches the Codex CLI's own
2
4
  // safe default). "danger-full-access" removes all filesystem guardrails and
3
5
  // must be an explicit opt-in via the UI/session setting, never the default.
6
+ //
7
+ // The approval default is "on-request". "on-failure" is not a policy of its
8
+ // own in current Codex releases (it is an alias of "on-request"), so a saved
9
+ // "on-failure" is read as the value it means.
4
10
  var CODEX_DEFAULTS = {
5
- approval: "on-failure",
11
+ approval: "on-request",
6
12
  sandbox: "workspace-write",
7
13
  webSearch: "live",
8
14
  };
9
15
 
10
16
  function getCodexConfig(sm) {
11
17
  return {
12
- approval: (sm && sm.codexApproval) || CODEX_DEFAULTS.approval,
18
+ approval: sm && sm.codexApproval ? normalizeApprovalPolicy(sm.codexApproval) : CODEX_DEFAULTS.approval,
13
19
  sandbox: (sm && sm.codexSandbox) || CODEX_DEFAULTS.sandbox,
14
20
  webSearch: (sm && sm.codexWebSearch) || CODEX_DEFAULTS.webSearch,
15
21
  };
@@ -11,6 +11,22 @@ var { scanWorktrees, isWorktree } = require("./worktree");
11
11
  var worktreeRegistry = {}; // parentSlug -> [wtSlug, ...]
12
12
  var worktreeTimers = {}; // parentSlug -> intervalId
13
13
  var worktreeScanning = {}; // parentSlug -> boolean (mutex)
14
+ // Set when shutdown begins and never cleared: a rescan that fires from then on
15
+ // would re-add worktrees (and create adapters for them) to projects that were
16
+ // just destroyed, inside the shutdown's force-exit window.
17
+ var rescansStopped = false;
18
+
19
+ /**
20
+ * Stop every worktree rescan timer and make any rescan or registration that
21
+ * still arrives a no-op. Shutdown calls this before it destroys the projects.
22
+ */
23
+ function stopWorktreeRescans() {
24
+ rescansStopped = true;
25
+ Object.keys(worktreeTimers).forEach(function (parentSlug) {
26
+ clearInterval(worktreeTimers[parentSlug]);
27
+ delete worktreeTimers[parentSlug];
28
+ });
29
+ }
14
30
 
15
31
  function isWorktreeSlug(slug) {
16
32
  return slug.indexOf("--") !== -1;
@@ -25,6 +41,7 @@ function isWorktreeSlug(slug) {
25
41
  * @param {string} parentOwnerId - owner user ID
26
42
  */
27
43
  function scanAndRegisterWorktrees(relay, parentPath, parentSlug, parentIcon, parentOwnerId) {
44
+ if (rescansStopped) return;
28
45
  if (isWorktree(parentPath)) return;
29
46
  var worktrees = scanWorktrees(parentPath);
30
47
  if (worktrees.length === 0) return;
@@ -59,6 +76,7 @@ function scanAndRegisterWorktrees(relay, parentPath, parentSlug, parentIcon, par
59
76
  * @param {object} [config] - daemon config (optional, for broadcasting project count)
60
77
  */
61
78
  function rescanWorktrees(relay, parentPath, parentSlug, parentIcon, parentOwnerId, config) {
79
+ if (rescansStopped) return;
62
80
  if (worktreeScanning[parentSlug]) return;
63
81
  worktreeScanning[parentSlug] = true;
64
82
  try {
@@ -193,6 +211,7 @@ module.exports = {
193
211
  isWorktreeSlug: isWorktreeSlug,
194
212
  scanAndRegisterWorktrees: scanAndRegisterWorktrees,
195
213
  rescanWorktrees: rescanWorktrees,
214
+ stopWorktreeRescans: stopWorktreeRescans,
196
215
  cleanupWorktreesForParent: cleanupWorktreesForParent,
197
216
  getFilteredRemovedProjects: getFilteredRemovedProjects,
198
217
  registerWorktreeSlug: registerWorktreeSlug,