@clagentic/console 1.10.0-beta.4 → 1.11.0-beta.1

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 (77) hide show
  1. package/README.md +14 -0
  2. package/bin/cli.js +15 -3
  3. package/lib/agents.js +1 -55
  4. package/lib/bash-auto-approve.js +133 -0
  5. package/lib/build-identity.js +23 -5
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-check.js +0 -62
  8. package/lib/build-update-offer.js +23 -13
  9. package/lib/build-update-restart.js +59 -43
  10. package/lib/cli/schedule-input-subcommands.js +327 -0
  11. package/lib/cli/session-subcommands.js +100 -17
  12. package/lib/client-build-id.js +56 -0
  13. package/lib/daemon.js +20 -5
  14. package/lib/injected-sender.js +225 -0
  15. package/lib/message-sender-record.js +133 -0
  16. package/lib/pending-prompts.js +55 -0
  17. package/lib/permission-mode-policy.js +63 -0
  18. package/lib/permission-summary.js +67 -0
  19. package/lib/project-connection.js +2 -1
  20. package/lib/project-external-trigger.js +9 -1
  21. package/lib/project-loop.js +26 -20
  22. package/lib/project-prompt-responses.js +20 -14
  23. package/lib/project-sessions.js +73 -21
  24. package/lib/project-user-message.js +18 -47
  25. package/lib/project.js +36 -62
  26. package/lib/public/app.js +3 -5
  27. package/lib/public/css/channel-layout.css +20 -0
  28. package/lib/public/css/diagnostics.css +7 -0
  29. package/lib/public/css/input.css +78 -0
  30. package/lib/public/css/menus.css +17 -0
  31. package/lib/public/modules/app-connection.js +18 -1
  32. package/lib/public/modules/app-messages.js +19 -17
  33. package/lib/public/modules/app-panels.js +9 -2
  34. package/lib/public/modules/app-rate-limit.js +63 -87
  35. package/lib/public/modules/app-rendering.js +37 -6
  36. package/lib/public/modules/at-agents.js +8 -0
  37. package/lib/public/modules/build-guard.js +61 -0
  38. package/lib/public/modules/build-update-detail.js +1 -4
  39. package/lib/public/modules/diagnostics.js +98 -9
  40. package/lib/public/modules/injected-identity.js +78 -0
  41. package/lib/public/modules/injected-label.js +62 -0
  42. package/lib/public/modules/input.js +64 -114
  43. package/lib/public/modules/mode-options.js +19 -16
  44. package/lib/public/modules/rate-limit-state.js +47 -22
  45. package/lib/public/modules/schedule-panel.js +234 -0
  46. package/lib/public/modules/schedule-time.js +193 -0
  47. package/lib/public/modules/scheduled-input-actions.js +19 -0
  48. package/lib/runtime-env.js +4 -0
  49. package/lib/scheduled-input/ipc.js +92 -0
  50. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  51. package/lib/scheduled-input/records.js +350 -0
  52. package/lib/scheduled-input/service.js +743 -0
  53. package/lib/scheduled-input/store.js +132 -0
  54. package/lib/scheduled-input/ws.js +194 -0
  55. package/lib/sdk-bridge.js +137 -152
  56. package/lib/sdk-message-processor.js +13 -5
  57. package/lib/sdk-skill-discovery.js +17 -0
  58. package/lib/sender-ref.js +109 -0
  59. package/lib/server.js +28 -8
  60. package/lib/session-directory.js +224 -0
  61. package/lib/session-file-scan.js +55 -0
  62. package/lib/session-input-ipc.js +20 -0
  63. package/lib/session-input.js +355 -19
  64. package/lib/session-name-holder.js +82 -0
  65. package/lib/session-resume.js +1 -0
  66. package/lib/sessions.js +44 -0
  67. package/lib/turn-initiator.js +6 -2
  68. package/lib/ws-schema.js +15 -7
  69. package/lib/yoke/adapters/claude-worker.js +3 -1
  70. package/lib/yoke/adapters/claude.js +13 -7
  71. package/lib/yoke/adapters/codex.js +18 -5
  72. package/lib/yoke/adapters/permission-relay.js +9 -0
  73. package/lib/yoke/interface.js +7 -1
  74. package/package.json +1 -1
  75. package/scripts/check-test-count.js +1 -1
  76. package/scripts/install-local-test.js +45 -1
  77. package/scripts/postinstall.js +1 -0
@@ -0,0 +1,109 @@
1
+ // sender-ref.js - the plain reference a console-started agent process carries to
2
+ // its own console session, and how the daemon resolves one.
3
+ //
4
+ // Part of the console's session-record format. Two non-secret variables are set
5
+ // in the environment of every Claude process the console starts, whatever
6
+ // identity provider is configured:
7
+ //
8
+ // CLAGENTIC_CONSOLE_PROJECT the project slug the session belongs to
9
+ // CLAGENTIC_CONSOLE_SESSION_ID the console session id (localId) in that project
10
+ //
11
+ // The pair is not an identity assertion and grants nothing. send-input,
12
+ // open-session and a file-drop writer pass it along; the daemon looks it up in
13
+ // its OWN session store and records the sender as "extracted". It is not proof
14
+ // against a same-user process copying the variables; only an attested sender is.
15
+
16
+ var PROJECT_ENV = "CLAGENTIC_CONSOLE_PROJECT";
17
+ var SESSION_ENV = "CLAGENTIC_CONSOLE_SESSION_ID";
18
+
19
+ var SESSION_ID_RE = /^[0-9]{1,9}$/;
20
+
21
+ // The environment additions for a session, or {} when it has no usable reference.
22
+ function envFor(ref) {
23
+ if (!ref || typeof ref.project !== "string" || !ref.project) return {};
24
+ var id = String(ref.sessionId);
25
+ if (!SESSION_ID_RE.test(id)) return {};
26
+ var out = {};
27
+ out[PROJECT_ENV] = ref.project;
28
+ out[SESSION_ENV] = id;
29
+ return out;
30
+ }
31
+
32
+ // Removes any inherited reference: the console sets it only for a session it
33
+ // started, so a daemon launched from inside a session must not pass its own on.
34
+ function strip(env) {
35
+ delete env[PROJECT_ENV];
36
+ delete env[SESSION_ENV];
37
+ return env;
38
+ }
39
+
40
+ // The reference a caller process holds, from its environment. null when absent.
41
+ function fromEnv(env) {
42
+ env = env || {};
43
+ var project = env[PROJECT_ENV];
44
+ var sessionId = env[SESSION_ENV];
45
+ if (typeof project !== "string" || !project || typeof sessionId !== "string" || !sessionId) return null;
46
+ return { project: project, sessionId: sessionId };
47
+ }
48
+
49
+ // The one label for a session, "<agent>@<project>" or, with no named agent,
50
+ // "<vendor>@<project>". null when it has neither. The chat's sender label and
51
+ // the session directory's addresses are both this.
52
+ function labelFor(agent, vendor, project) {
53
+ var who = agent || vendor;
54
+ if (!who || !project) return null;
55
+ return who + "@" + project;
56
+ }
57
+
58
+ function isLive(session) {
59
+ return !!(session.isProcessing || session.queryInstance || (session.worker && session.messageQueue === "worker"));
60
+ }
61
+
62
+ // Resolves a reference against the daemon's own store. Returns
63
+ // { project, sessionId, agent, vendor, cliSessionId, name } or null. null (never a guess) when
64
+ // the project or session is not held, the session has no live runtime (the
65
+ // caller of a reference is a running process of that session), or it runs as
66
+ // another OS user (the daemon's socket and trigger directory admit only its own).
67
+ //
68
+ // getProject(slug) -> project context | null
69
+ function resolve(getProject, ref) {
70
+ if (!ref || typeof ref.project !== "string" || !ref.project) return null;
71
+ var id = typeof ref.sessionId === "number" ? String(ref.sessionId) : ref.sessionId;
72
+ if (typeof id !== "string" || !SESSION_ID_RE.test(id)) return null;
73
+ var project = getProject(ref.project);
74
+ if (!project || !project.sm || !project.sm.sessions) return null;
75
+ var found = null;
76
+ project.sm.sessions.forEach(function (s) {
77
+ if (!found && String(s.localId) === id) found = s;
78
+ });
79
+ if (!found || !isLive(found)) return null;
80
+ if (typeof project.getLinuxUserForSession === "function" && project.getLinuxUserForSession(found)) return null;
81
+ // Required here: the worker loads this module for its env helpers only.
82
+ var slugifyAgentName = require("./agents").slugifyAgentName;
83
+ var agent = found.agentName || null;
84
+ var vendor = found.vendor || project.sm.defaultVendor || null;
85
+ var name = labelFor(agent, vendor, ref.project);
86
+ if (!name) return null;
87
+ return {
88
+ project: ref.project,
89
+ sessionId: id,
90
+ agent: agent,
91
+ agentSlug: agent ? slugifyAgentName(agent) : null,
92
+ vendor: vendor,
93
+ // The vendor's own session id: unlike the console id it survives a daemon
94
+ // restart, so it can prove later that a console id still names this session.
95
+ cliSessionId: found.cliSessionId || null,
96
+ name: name,
97
+ };
98
+ }
99
+
100
+ module.exports = {
101
+ labelFor: labelFor,
102
+ isLive: isLive,
103
+ PROJECT_ENV: PROJECT_ENV,
104
+ SESSION_ENV: SESSION_ENV,
105
+ envFor: envFor,
106
+ strip: strip,
107
+ fromEnv: fromEnv,
108
+ resolve: resolve,
109
+ };
package/lib/server.js CHANGED
@@ -23,6 +23,7 @@ var { resolveEffectiveProtocol } = require("./effective-protocol");
23
23
  var { createProjectAccess } = require("./project-access");
24
24
  var { checkWsOrigin } = require("./ws-origin");
25
25
  var sessionReclaim = require("./session-reclaim");
26
+ var clientBuildId = require("./client-build-id");
26
27
 
27
28
  var https = require("https");
28
29
  var pkg = require("../package.json");
@@ -70,17 +71,13 @@ var MIME_TYPES = {
70
71
  function serveStatic(urlPath, res) {
71
72
  if (urlPath === "/") urlPath = "/index.html";
72
73
 
73
- // Special case: inject version into sw.js cache name at serve time
74
+ // Special case: stamp the sw.js cache name with the build id at serve time.
75
+ // The build id, not the package version: consecutive builds can share a
76
+ // version, and the worker must change bytes on every restart onto a new build.
74
77
  if (urlPath === "/sw.js") {
75
78
  var swPath = path.join(publicDir, "sw.js");
76
79
  try {
77
- var swContent = fs.readFileSync(swPath, "utf8");
78
- var appVersion = pkg.version;
79
- // Replace the static cache name with a version-stamped one
80
- swContent = swContent.replace(
81
- /var CACHE_NAME = "clagentic-console-offline-[^"]*"/,
82
- 'var CACHE_NAME = "clagentic-console-offline-v' + appVersion + '"'
83
- );
80
+ var swContent = clientBuildId.stampServiceWorker(fs.readFileSync(swPath, "utf8"), clientBuildId.get());
84
81
  res.writeHead(200, {
85
82
  "Content-Type": "application/javascript; charset=utf-8",
86
83
  "Cache-Control": "no-cache",
@@ -401,6 +398,22 @@ function createServer(opts) {
401
398
  // send-input).
402
399
  var _sessionInput = require("./session-input").createSessionInput({
403
400
  getProject: function (slug) { return projects.get(slug) || null; },
401
+ listProjects: function () {
402
+ var held = [];
403
+ projects.forEach(function (ctx, slug) { held.push({ slug: slug, project: ctx }); });
404
+ return held;
405
+ },
406
+ });
407
+ // Scheduled input for every project: one persisted list per project, one
408
+ // timer, and the firing through the same _sessionInput (lib/scheduled-input/).
409
+ var _scheduledInput = require("./scheduled-input/service").createScheduledInputService({
410
+ dir: path.join(CONFIG_DIR, "scheduled-input"),
411
+ getProject: function (slug) { return projects.get(slug) || null; },
412
+ sessionInput: _sessionInput,
413
+ publish: require("./scheduled-input/ws").createPublisher({
414
+ getProject: function (slug) { return projects.get(slug) || null; },
415
+ listFor: function (slug, session) { return _scheduledInput.armedForSession(slug, session); },
416
+ }),
404
417
  });
405
418
  var _externalTrigger = attachExternalTrigger({
406
419
  triggersDir: EXTERNAL_TRIGGERS_DIR,
@@ -724,6 +737,7 @@ function createServer(opts) {
724
737
  res.end(JSON.stringify({
725
738
  projects: projectList,
726
739
  version: currentVersion,
740
+ buildId: clientBuildId.get(),
727
741
  authenticated: true,
728
742
  liteInstalled: liteStatus.installed,
729
743
  liteHome: liteStatus.liteHome,
@@ -1432,6 +1446,7 @@ function createServer(opts) {
1432
1446
  // when a session in this project is deleted — see onSessionDeleted's
1433
1447
  // header above.
1434
1448
  onSessionDeleted: function (localId) { onSessionDeleted(slug, localId); },
1449
+ scheduledInput: _scheduledInput,
1435
1450
  // lr-13c047: expose the non-switch "mark read" clear path (see
1436
1451
  // markCrossProjectRead's header above) so lib/project-sessions.js can
1437
1452
  // wire a client-initiated mark_cross_project_read WS message without
@@ -1499,6 +1514,7 @@ function createServer(opts) {
1499
1514
  isUserOnline: isUserOnline,
1500
1515
  });
1501
1516
  projects.set(slug, ctx);
1517
+ _scheduledInput.attachProject(slug);
1502
1518
  // ctx.warmup() is now deferred to the first websocket connection into
1503
1519
  // this project (see project-connection.js handleConnection). Warming
1504
1520
  // every project at startup spawned a CodexAppServer and an mcp-bridge
@@ -1530,6 +1546,7 @@ function createServer(opts) {
1530
1546
  // A deliberate removal: its sessions are not recorded as resumable.
1531
1547
  var shutdownResult = ctx.destroy({ reason: "project_removed" });
1532
1548
  projects.delete(slug);
1549
+ _scheduledInput.detachProject(slug);
1533
1550
  if (shutdownResult && typeof shutdownResult.catch === "function") {
1534
1551
  shutdownResult.catch(function(err) {
1535
1552
  console.error("[server] Project destroy failed for " + slug + ":", err && err.message ? err.message : err);
@@ -1751,6 +1768,7 @@ function createServer(opts) {
1751
1768
 
1752
1769
  function destroyAll() {
1753
1770
  _externalTrigger.stopWatcher();
1771
+ _scheduledInput.stop();
1754
1772
  var shutdowns = [];
1755
1773
  var tally = sessionReclaim.createShutdownTally();
1756
1774
  projects.forEach(function (ctx, slug) {
@@ -1835,6 +1853,8 @@ function createServer(opts) {
1835
1853
  broadcastAll: broadcastAll,
1836
1854
  forEachProject: forEachProject,
1837
1855
  sessionInput: _sessionInput,
1856
+ scheduledInput: _scheduledInput,
1857
+ getProject: function (slug) { return projects.get(slug) || null; },
1838
1858
  destroyProject: removeProject,
1839
1859
  destroyAll: destroyAll,
1840
1860
  // Drain controller injection (lr-6b30).
@@ -0,0 +1,224 @@
1
+ // session-directory.js - discover the console's sessions and resolve an address
2
+ // to one of them. Read-only: nothing here changes a session or delivers input;
3
+ // lib/session-input.js does the delivery once an address has become a session id.
4
+ //
5
+ // The directory is the console's own session store as the daemon holds it: every
6
+ // session recorded on disk is loaded into its project's session manager at start,
7
+ // whether or not it has a runtime, so a session whose runtime was reaped is listed
8
+ // and addressable exactly like a running one. A session started outside the
9
+ // console is not in the store and is not listed.
10
+ //
11
+ // States:
12
+ // live a turn is running
13
+ // idle a runtime is attached and no turn is running
14
+ // reaped no runtime (idle reaper, daemon restart); input resumes it
15
+ //
16
+ // Addresses (the label format of lib/sender-ref.js):
17
+ // <agent>@<project> a session running that named agent
18
+ // <vendor>@<project> a PLAIN session (no named agent) on that vendor
19
+ // @<project> any session in the project
20
+ // Each form takes an optional "/<name>" after the project, naming one session by
21
+ // the name it was opened with (see validateName):
22
+ // <agent>@<project>/<name>, <vendor>@<project>/<name>, @<project>/<name>
23
+ //
24
+ // Resolution never guesses. Among the sessions an address matches, the highest
25
+ // state tier that has any match decides: live, then idle, then reaped. Exactly
26
+ // one there is the answer; several there are refused with candidates; a lower
27
+ // tier is not consulted once a higher one matched.
28
+
29
+ var senderRef = require("./sender-ref");
30
+ var { slugifyAgentName } = require("./agents");
31
+ var { isInjected } = require("./injected-sender");
32
+ var { pendingPrompts } = require("./pending-prompts");
33
+
34
+ var STATE = Object.freeze({ LIVE: "live", IDLE: "idle", REAPED: "reaped" });
35
+ var ANY_STATE = "any";
36
+ var STATE_FILTERS = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED, ANY_STATE]);
37
+
38
+ var MAX_ADDRESS_LENGTH = 192;
39
+ var ADDRESS_RE = /^([^@\s]*)@([^@\s]+)$/;
40
+
41
+ // Highest first: the order resolve() consults the tiers in.
42
+ var TIER_ORDER = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED]);
43
+
44
+ // A session name is a path-free token so it can follow the project after a "/"
45
+ // in an address. Project slugs never contain "/" (lib/config.js generateSlug).
46
+ var NAME_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
47
+
48
+ // Returns { name } (lowercased: names compare case-insensitively) or { error }.
49
+ function validateName(raw) {
50
+ if (typeof raw !== "string" || !raw) return { error: "session name must be a non-empty string" };
51
+ var name = raw.toLowerCase();
52
+ if (!NAME_RE.test(name)) {
53
+ return { error: "session name " + JSON.stringify(raw.slice(0, 40)) + " must be 1-32 characters of a-z, 0-9, \"-\" and \"_\", starting with a letter or digit" };
54
+ }
55
+ return { name: name };
56
+ }
57
+
58
+ function stateOf(session) {
59
+ if (!senderRef.isLive(session)) return STATE.REAPED;
60
+ return session.isProcessing ? STATE.LIVE : STATE.IDLE;
61
+ }
62
+
63
+ function isoOrNull(ms) {
64
+ return typeof ms === "number" && isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : null;
65
+ }
66
+
67
+ // One directory entry. slug is the project's slug, the same string the label
68
+ // carries.
69
+ function describe(slug, project, session, now) {
70
+ var agent = session.agentName || null;
71
+ var vendor = session.vendor || project.sm.defaultVendor || null;
72
+ return {
73
+ consoleSessionId: String(session.localId),
74
+ sessionId: session.cliSessionId || null,
75
+ project: slug,
76
+ agent: agent,
77
+ vendor: vendor,
78
+ label: senderRef.labelFor(agent, vendor, slug),
79
+ name: session.sessionName || null,
80
+ title: session.title || "",
81
+ state: stateOf(session),
82
+ lastActivity: isoOrNull(session.lastActivity || session.createdAt),
83
+ pendingPrompts: pendingPrompts(session, now),
84
+ };
85
+ }
86
+
87
+ // Newest first; ties keep the lower console id first so the order is stable.
88
+ function byRecency(a, b) {
89
+ var ta = a.lastActivity || "";
90
+ var tb = b.lastActivity || "";
91
+ if (ta !== tb) return ta < tb ? 1 : -1;
92
+ return Number(a.consoleSessionId) - Number(b.consoleSessionId);
93
+ }
94
+
95
+ // projects: [{ slug, project }] with project a context holding sm.sessions.
96
+ // A hidden session (a background helper) is not part of the directory, and a
97
+ // session that has no id from its vendor yet and no runtime was never recorded.
98
+ function collect(projects, now) {
99
+ var out = [];
100
+ var at = typeof now === "number" ? now : Date.now();
101
+ (projects || []).forEach(function (p) {
102
+ if (!p || !p.project || !p.project.sm || !p.project.sm.sessions) return;
103
+ p.project.sm.sessions.forEach(function (s) {
104
+ if (s.hidden) return;
105
+ if (!s.cliSessionId && !senderRef.isLive(s)) return;
106
+ out.push(describe(p.slug, p.project, s, at));
107
+ });
108
+ });
109
+ return out.sort(byRecency);
110
+ }
111
+
112
+ // filter: { project?, agent?, vendor?, state?, now? } (now: ms epoch for the
113
+ // prompt ages, default the current time). Returns { entries } or { error }.
114
+ function list(projects, filter) {
115
+ filter = filter || {};
116
+ var state = filter.state === undefined || filter.state === null ? ANY_STATE : filter.state;
117
+ if (STATE_FILTERS.indexOf(state) === -1) {
118
+ return { error: "unknown state " + JSON.stringify(String(state).slice(0, 32)) + " (accepted: " + STATE_FILTERS.join(", ") + ")" };
119
+ }
120
+ var agentSlug = filter.agent ? slugifyAgentName(filter.agent) : null;
121
+ if (filter.agent && !agentSlug) return { error: "agent must name an agent" };
122
+ var vendor = filter.vendor ? String(filter.vendor).toLowerCase() : null;
123
+ var entries = collect(projects, filter.now).filter(function (e) {
124
+ if (filter.project && e.project !== filter.project) return false;
125
+ if (agentSlug && slugifyAgentName(e.agent) !== agentSlug) return false;
126
+ if (vendor && String(e.vendor || "").toLowerCase() !== vendor) return false;
127
+ if (state !== ANY_STATE && e.state !== state) return false;
128
+ return true;
129
+ });
130
+ return { entries: entries };
131
+ }
132
+
133
+ // Returns { project, token } (token is "" for @<project>) or { error }, plus
134
+ // name when the address carries "/<name>".
135
+ function parseAddress(raw) {
136
+ if (typeof raw !== "string" || !raw) return { error: "address must be a non-empty string" };
137
+ if (raw.length > MAX_ADDRESS_LENGTH) return { error: "address is longer than " + MAX_ADDRESS_LENGTH + " characters" };
138
+ var m = ADDRESS_RE.exec(raw);
139
+ if (!m) return { error: "address " + JSON.stringify(raw.slice(0, 64)) + " is not <agent>@<project>, <vendor>@<project> or @<project>, each with an optional /<name>" };
140
+ var token = slugifyAgentName(m[1]);
141
+ if (m[1] && !token) return { error: "address " + JSON.stringify(raw.slice(0, 64)) + " names no agent or vendor" };
142
+ var slash = m[2].indexOf("/");
143
+ if (slash === -1) return { project: m[2], token: token };
144
+ var project = m[2].slice(0, slash);
145
+ var named = validateName(m[2].slice(slash + 1));
146
+ if (!project) return { error: "address " + JSON.stringify(raw.slice(0, 64)) + " names no project" };
147
+ if (named.error) return { error: named.error };
148
+ return { project: project, token: token, name: named.name };
149
+ }
150
+
151
+ // Which sessions an address names, among the entries of its project. A named
152
+ // session matches by its agent, a plain one by its vendor. A recorded identity
153
+ // ({ project, vendor, sessionId } with sessionId the vendor's own session id)
154
+ // names a session only when all three are equal.
155
+ function matchesOf(entries, parsed) {
156
+ return entries.filter(function (e) {
157
+ if (e.project !== parsed.project) return false;
158
+ if (parsed.sessionId !== undefined) {
159
+ return !!parsed.sessionId && e.sessionId === parsed.sessionId
160
+ && String(e.vendor || "").toLowerCase() === String(parsed.vendor || "").toLowerCase();
161
+ }
162
+ if (parsed.name !== undefined && e.name !== parsed.name) return false;
163
+ if (!parsed.token) return true;
164
+ if (e.agent) return slugifyAgentName(e.agent) === parsed.token;
165
+ return String(e.vendor || "").toLowerCase() === parsed.token;
166
+ });
167
+ }
168
+
169
+ // Resolves an address, or a recorded identity, against the entries (collect()).
170
+ // Never guesses:
171
+ // { match } exactly one session
172
+ // { candidates } more than one; the caller chooses with a session id
173
+ // { none: true } no session
174
+ // The highest state tier (live, idle, reaped) holding any match decides: one
175
+ // there is the answer, several are the candidates, and lower tiers are not
176
+ // looked at. A named address (parsed.name) is exact: it matches only sessions
177
+ // of that name, so it never falls to a different session; the tiers then only
178
+ // separate same-named twins (a reaped one beside a running one).
179
+ function resolve(entries, parsed) {
180
+ var matches = matchesOf(entries, parsed);
181
+ for (var i = 0; i < TIER_ORDER.length; i++) {
182
+ var tier = matches.filter(function (e) { return e.state === TIER_ORDER[i]; });
183
+ if (tier.length === 1) return { match: tier[0] };
184
+ if (tier.length > 1) return { candidates: tier };
185
+ }
186
+ return { none: true };
187
+ }
188
+
189
+ // The sender of the most recent injected message in a session's history.
190
+ // Returns { project, vendor, cliSessionId, name } or { reason } saying why there
191
+ // is none. Only an extracted sender names a session; a declared or undeclared
192
+ // one cannot be answered. The sender is identified by project, vendor and the
193
+ // vendor's own session id, all recorded together at injection time; an entry
194
+ // lacking any of them (one recorded before they were kept) has no answerable
195
+ // sender. The console session id is deliberately not returned. Searches the
196
+ // history window held in memory.
197
+ function lastInjectedSender(history) {
198
+ for (var i = (history || []).length - 1; i >= 0; i--) {
199
+ var entry = history[i];
200
+ if (!isInjected(entry)) continue;
201
+ if (entry.senderKind !== "extracted" || !entry.senderProject) {
202
+ return { reason: "the most recent injected message in this session has no recorded sender session (its sender is " + (entry.senderKind || "unrecorded") + ")" };
203
+ }
204
+ if (!entry.senderVendor || !entry.senderCliSessionId) {
205
+ return { reason: "reply refused: the most recent injected message recorded no vendor or vendor session id for its sender (it predates them, or the sender had no vendor session id yet), so the sender session cannot be proven" };
206
+ }
207
+ return { project: entry.senderProject, vendor: entry.senderVendor, cliSessionId: entry.senderCliSessionId, name: entry.fromName || null };
208
+ }
209
+ // `none` tells a caller holding only a window of the history that this is a
210
+ // miss in that window, not proof that the session never received one.
211
+ return { none: true, reason: "this session has received no injected message to reply to" };
212
+ }
213
+
214
+ module.exports = {
215
+ STATE: STATE,
216
+ STATE_FILTERS: STATE_FILTERS,
217
+ stateOf: stateOf,
218
+ collect: collect,
219
+ list: list,
220
+ parseAddress: parseAddress,
221
+ validateName: validateName,
222
+ resolve: resolve,
223
+ lastInjectedSender: lastInjectedSender,
224
+ };
@@ -0,0 +1,55 @@
1
+ // session-file-scan.js - a bounded reverse scan of a session's JSONL file.
2
+ // The file is read backwards in fixed-size chunks and the scan stops at the
3
+ // first (newest) entry the predicate accepts, so the memory held is the chunk
4
+ // plus the one line being assembled, never the file. Line 0 of a session file
5
+ // is its meta record and is never offered to the predicate.
6
+
7
+ var fs = require("fs");
8
+
9
+ var DEFAULT_CHUNK_BYTES = 64 * 1024;
10
+ var NEWLINE = 0x0a;
11
+
12
+ // Offers each history entry of the file at `filePath`, newest first, to
13
+ // `accept(entry)`; returns the first entry it accepts, or null when none does.
14
+ // A missing or unreadable file throws (the caller decides what that means). A
15
+ // line that is not JSON is skipped, as the full-history parse skips it.
16
+ function findNewestEntry(filePath, accept, chunkBytes) {
17
+ var chunkSize = chunkBytes > 0 ? chunkBytes : DEFAULT_CHUNK_BYTES;
18
+ var fd = fs.openSync(filePath, "r");
19
+ try {
20
+ var pos = fs.fstatSync(fd).size;
21
+ // Bytes of a line whose start lies in an earlier chunk. Kept as bytes, not
22
+ // text, so a multibyte character split by a chunk boundary stays intact.
23
+ var carry = Buffer.alloc(0);
24
+ var chunk = Buffer.alloc(chunkSize);
25
+
26
+ function offer(lineBuf) {
27
+ if (lineBuf.length === 0) return null;
28
+ var entry;
29
+ try { entry = JSON.parse(lineBuf.toString("utf8")); } catch { return null; }
30
+ return accept(entry) ? entry : null;
31
+ }
32
+
33
+ while (pos > 0) {
34
+ var n = Math.min(chunkSize, pos);
35
+ pos -= n;
36
+ var got = fs.readSync(fd, chunk, 0, n, pos);
37
+ var buf = Buffer.concat([chunk.subarray(0, got), carry]);
38
+ var end = buf.length;
39
+ var nl = buf.lastIndexOf(NEWLINE, end - 1);
40
+ while (nl !== -1) {
41
+ var hit = offer(buf.subarray(nl + 1, end));
42
+ if (hit) return hit;
43
+ end = nl;
44
+ nl = end > 0 ? buf.lastIndexOf(NEWLINE, end - 1) : -1;
45
+ }
46
+ carry = Buffer.from(buf.subarray(0, end));
47
+ }
48
+ // What remains is line 0: the meta record, which is not history.
49
+ return null;
50
+ } finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ }
54
+
55
+ module.exports = { findNewestEntry: findNewestEntry, DEFAULT_CHUNK_BYTES: DEFAULT_CHUNK_BYTES };
@@ -9,10 +9,16 @@ function handleSessionCommand(sessionInput, msg) {
9
9
  if (msg.cmd === "open_session") {
10
10
  return sessionInput.openSession({
11
11
  projectSlug: msg.projectSlug,
12
+ to: msg.to,
12
13
  prompt: msg.prompt,
13
14
  contextNote: msg.contextNote,
15
+ from: msg.from,
16
+ fromSession: msg.fromSession,
17
+ senderProject: msg.senderProject,
18
+ senderSessionId: msg.senderSessionId,
14
19
  vendor: msg.vendor,
15
20
  agentName: msg.agentName,
21
+ sessionName: msg.sessionName,
16
22
  sessionVisibility: msg.sessionVisibility,
17
23
  initiator: msg.initiator,
18
24
  });
@@ -21,11 +27,25 @@ function handleSessionCommand(sessionInput, msg) {
21
27
  return sessionInput.sendInput({
22
28
  projectSlug: msg.projectSlug,
23
29
  sessionId: msg.sessionId,
30
+ to: msg.to,
31
+ reply: msg.reply,
24
32
  prompt: msg.prompt,
25
33
  contextNote: msg.contextNote,
34
+ from: msg.from,
35
+ fromSession: msg.fromSession,
36
+ senderProject: msg.senderProject,
37
+ senderSessionId: msg.senderSessionId,
26
38
  initiator: msg.initiator,
27
39
  });
28
40
  }
41
+ if (msg.cmd === "list_sessions") {
42
+ return sessionInput.listSessions({
43
+ projectSlug: msg.projectSlug,
44
+ agentName: msg.agentName,
45
+ vendor: msg.vendor,
46
+ state: msg.state,
47
+ });
48
+ }
29
49
  return undefined;
30
50
  }
31
51