omni-notify-mcp 1.3.376 → 1.3.378
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/agentGateway.js +29 -9
- package/dist/gateway/claudeProvider.js +1 -0
- package/dist/gateway/conversations.js +92 -5
- package/dist/gateway/mcpDoor.js +17 -12
- package/dist/gateway/provider.js +0 -2
- package/dist/gateway/restDoor.js +8 -9
- package/dist/gateway/terminalDoor.js +8 -9
- package/dist/gateway/terminalPage.js +3 -3
- package/dist/shared/agentSession.js +263 -18
- package/dist/shared/webhost/autoSwitch.cjs +116 -1
- package/package.json +1 -1
package/dist/agentGateway.js
CHANGED
|
@@ -12,9 +12,8 @@
|
|
|
12
12
|
import { fileURLToPath } from "url";
|
|
13
13
|
import { splitForNotify } from "./chunk.js";
|
|
14
14
|
import { masterMuted } from "./notify.js";
|
|
15
|
-
import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
|
|
15
|
+
import { appendEvent, CONVERSATION_MUTED_MESSAGE, conversationRefusal, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversations.js";
|
|
16
16
|
import { SessionDriver } from "./gateway/sessionDriver.js";
|
|
17
|
-
import { DEFAULT_PROVIDER } from "./gateway/provider.js";
|
|
18
17
|
import { clearOpenCodeLogs } from "./gateway/opencodeProvider.js";
|
|
19
18
|
import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
|
|
20
19
|
export const AGENT_PREFIX = "!";
|
|
@@ -54,7 +53,7 @@ function driverOptions() {
|
|
|
54
53
|
guardDir,
|
|
55
54
|
spare: process.env.NOTIFY_AGENT_SPARE === "1" ? true : undefined,
|
|
56
55
|
clis: {
|
|
57
|
-
...(script ? {
|
|
56
|
+
...(script ? { claude: { cmd: process.execPath, args: [script] } } : {}),
|
|
58
57
|
...(copilot ? { copilot: { cmd: process.execPath, args: [copilot] } } : {}),
|
|
59
58
|
...(codex ? { codex: { cmd: process.execPath, args: [codex] } } : {}),
|
|
60
59
|
...(opencode ? { opencode: { cmd: process.execPath, args: [opencode] } } : {}),
|
|
@@ -112,9 +111,9 @@ export class AgentGateway {
|
|
|
112
111
|
void this.awaitTurn(c.id, Number(turn), (part) => door(c, part), CARRIAGE[c.platform], pending).catch((err) => appendEvent(c.id, { role: "system", kind: "status", text: `❌ The answer could not be sent to this ${c.platform} thread after the BN restart: ${err instanceof Error ? err.message : String(err)}` }));
|
|
113
112
|
}
|
|
114
113
|
}
|
|
115
|
-
/** No turn running or queued, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
|
|
114
|
+
/** No turn running or queued, no chat message waiting on its conversation's creation, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
|
|
116
115
|
quiet() {
|
|
117
|
-
return this.driver.quiet() && [...this.turns.values()].every((turns) => turns.size === 0);
|
|
116
|
+
return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
|
|
118
117
|
}
|
|
119
118
|
/** Gives the store back when this process hands the gateway over. */
|
|
120
119
|
async shutdown() {
|
|
@@ -177,6 +176,9 @@ export class AgentGateway {
|
|
|
177
176
|
return;
|
|
178
177
|
if (refusal !== undefined)
|
|
179
178
|
return reply(refusal);
|
|
179
|
+
// NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
|
|
180
|
+
for (let pending = creationPending(key); pending !== undefined; pending = creationPending(key))
|
|
181
|
+
await pending;
|
|
180
182
|
const open = carriage.conversationOf(key);
|
|
181
183
|
if (act.kind === "stop") {
|
|
182
184
|
const stopped = carriage.stopOf(key);
|
|
@@ -212,10 +214,28 @@ export class AgentGateway {
|
|
|
212
214
|
// A conversation opened in a thread the chat already reads starts reading after what was read, never from the thread's root again.
|
|
213
215
|
// NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
|
|
214
216
|
const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
217
|
+
const turn = {};
|
|
218
|
+
const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
|
|
219
|
+
const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
|
|
220
|
+
// NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
|
|
221
|
+
const told = open === undefined ? [] : [this.told(created.id, 1, `🆕 An independent ask: it runs in its own conversation ${created.id.slice(0, 8)} while ${open.id.slice(0, 8)} keeps working.`)];
|
|
222
|
+
turn.answered = this.awaitTurn(created.id, 1, reply, carriage, told);
|
|
223
|
+
turn.id = created.id;
|
|
224
|
+
return created;
|
|
225
|
+
})]);
|
|
226
|
+
if (creation.status === "rejected") {
|
|
227
|
+
// NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
|
|
228
|
+
if (turn.id === undefined)
|
|
229
|
+
throw creation.reason;
|
|
230
|
+
const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
|
|
231
|
+
process.stderr.write(`[agent-gateway] conversation ${turn.id.slice(0, 8)}: the unread-room notice could not be written (${reason}); the turn runs on and its answer is delivered\n`);
|
|
232
|
+
this.deliver(this.told(turn.id, 1, `⚠️ No CLI was named and DeepAgent's subscription room could not be read; that notice could not be written to this conversation: ${reason}`));
|
|
233
|
+
return turn.answered;
|
|
234
|
+
}
|
|
235
|
+
// NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
|
|
236
|
+
if (creation.value.notice !== undefined)
|
|
237
|
+
this.deliver({ ...creation.value.notice, id: creation.value.made.id });
|
|
238
|
+
return turn.answered;
|
|
219
239
|
}
|
|
220
240
|
// NULL-OK: field email is OPTIONAL and therefore it is ok to check for NULL
|
|
221
241
|
if (origin.email !== undefined)
|
|
@@ -15,7 +15,7 @@ import { EventEmitter } from "events";
|
|
|
15
15
|
import { basename, dirname, join, resolve } from "path";
|
|
16
16
|
import { CONFIG_DIR, masterMuted } from "../notify.js";
|
|
17
17
|
import { PROVIDER_NAMES, providerFor } from "./providers.js";
|
|
18
|
-
import
|
|
18
|
+
import autoSwitch from "../shared/webhost/autoSwitch.cjs";
|
|
19
19
|
import { workspacesFile, workspacesHere } from "../shared/webhost/workspaceList.js";
|
|
20
20
|
/** The title the agent's session carries in Claude's session list: the project and the first request, so one session is told from another at a glance. A conversation opened with no message yet is named by its project alone. */
|
|
21
21
|
export function titleOf(meta, events) {
|
|
@@ -211,6 +211,10 @@ export function inScope(meta, viewer) {
|
|
|
211
211
|
// NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
|
|
212
212
|
return meta.chat !== undefined && meta.chat === viewer.creator;
|
|
213
213
|
}
|
|
214
|
+
/** The creator a scoped caller stamps on a conversation it creates outside its own folder — at the workspace root (#4157) — so it still reads it; one in its own folder is in its scope already and carries none. */
|
|
215
|
+
export function creatorOf(viewer, folder) {
|
|
216
|
+
return viewer === undefined || sameFolder(folder, viewer.folder) ? undefined : viewer.creator;
|
|
217
|
+
}
|
|
214
218
|
/** A viewer is refused a conversation outside its scope in the words a missing one gets: it never learns another workspace's work exists. */
|
|
215
219
|
export function requireInScope(meta, viewer) {
|
|
216
220
|
if (!inScope(meta, viewer))
|
|
@@ -609,14 +613,97 @@ export function createdFolder(project) {
|
|
|
609
613
|
throw new GatewayError(400, `a new session needs the workspace it runs in: send project as exactly one of ${allowedProjects().join(", ")}`);
|
|
610
614
|
return allowedFolder(project);
|
|
611
615
|
}
|
|
612
|
-
/** The agent CLI a session is CREATED on,
|
|
616
|
+
/** The agent CLI a session is CREATED on, as its creation named it (#3640): one this gateway runs, or the refusal saying which. */
|
|
613
617
|
export function namedProvider(provider) {
|
|
614
|
-
if (provider === undefined || (typeof provider === "string" && provider.trim() === ""))
|
|
615
|
-
return DEFAULT_PROVIDER;
|
|
616
618
|
if (typeof provider !== "string" || providerFor(provider) === undefined)
|
|
617
|
-
throw new GatewayError(400, `provider must be exactly one of ${PROVIDER_NAMES.join(", ")}, or left out for
|
|
619
|
+
throw new GatewayError(400, `provider must be exactly one of ${PROVIDER_NAMES.join(", ")}, or left out for the one with subscription room`);
|
|
618
620
|
return provider;
|
|
619
621
|
}
|
|
622
|
+
// GATE: DeepAgent's door, which a creation naming no provider asks for each provider's room, may be moved ONLY under the test gate — to NOTIFY_DEEPAGENT_API, or with none named to the discard port, which refuses at once so a suite never reads this box's live accounts; without the gate it is DeepAgent's own door.
|
|
623
|
+
function deepagentDoor() {
|
|
624
|
+
if (process.env.NOTIFY_MCP_TEST_ENDPOINTS !== "1")
|
|
625
|
+
return undefined;
|
|
626
|
+
return process.env.NOTIFY_DEEPAGENT_API ?? "http://127.0.0.1:9/mcp";
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* The agent CLI a session is CREATED on (#3640): the one its creation named, or — named none (#4157) — the shared
|
|
630
|
+
* subscription-first pick (`autoProvider`, the one FleetView's AUTO runs) over every CLI this gateway runs — at the
|
|
631
|
+
* workspace root only those that load every project's rules there — weighed by DeepAgent's `provider_room` read for the folder.
|
|
632
|
+
*/
|
|
633
|
+
async function pickedCli(provider, folder) {
|
|
634
|
+
if (provider !== undefined && !(typeof provider === "string" && provider.trim() === ""))
|
|
635
|
+
return { provider: namedProvider(provider) };
|
|
636
|
+
const startable = isRootFolder(folder) ? PROVIDER_NAMES.filter((name) => providerFor(name).routesAtRoot === true) : PROVIDER_NAMES;
|
|
637
|
+
if (startable.length === 1) {
|
|
638
|
+
process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${startable[0]}, the one CLI that routes from there\n`);
|
|
639
|
+
return { provider: startable[0] };
|
|
640
|
+
}
|
|
641
|
+
let rooms;
|
|
642
|
+
let unreadBecause;
|
|
643
|
+
try {
|
|
644
|
+
rooms = await autoSwitch.readProviderRooms(folder, deepagentDoor());
|
|
645
|
+
}
|
|
646
|
+
catch (err) {
|
|
647
|
+
if (!(err instanceof autoSwitch.RoomReadError))
|
|
648
|
+
throw err;
|
|
649
|
+
// OWNER: a room DeepAgent could not read is a reading, never a refusal of the creation — every provider is taken as unread with the reason (never as spent), the pick lands on the first subscription in the order, and the conversation it makes carries the reason on its own page.
|
|
650
|
+
rooms = autoSwitch.unreadRooms(err.message);
|
|
651
|
+
unreadBecause = err.message;
|
|
652
|
+
}
|
|
653
|
+
const picked = autoSwitch.autoProvider(PROVIDER_NAMES, rooms, startable);
|
|
654
|
+
const unread = [...new Set(Object.values(rooms).flatMap((r) => (r?.state === "unread" ? [r.reason] : [])))];
|
|
655
|
+
const words = Object.entries(rooms).map(([id, r]) => `${id} ${r?.state}`).join(", ") + (unread.length === 0 ? "" : ` — unread: ${unread.join("; ")}`);
|
|
656
|
+
process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick over ${words}\n`);
|
|
657
|
+
return { provider: picked, ...(unreadBecause === undefined ? {} : { unreadBecause }) };
|
|
658
|
+
}
|
|
659
|
+
/** #4157 — the creations still waiting on their CLI pick, by the chat they are made for: an ask from that chat routes only once they exist, so it is never doubled beside one nor sent past it. */
|
|
660
|
+
const creating = new Map();
|
|
661
|
+
/** What an ask from `chat` waits on before it routes: every creation for it still picking its CLI, or undefined — returned without yielding — when there is none. */
|
|
662
|
+
export function creationPending(chat) {
|
|
663
|
+
const pending = creating.get(chat);
|
|
664
|
+
// NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
|
|
665
|
+
return pending === undefined ? undefined : Promise.allSettled([...pending]);
|
|
666
|
+
}
|
|
667
|
+
/** Every creation still picking its CLI, whichever chat it is for or none: the gateway does not pass to another process while one is, or the call it carries is dropped. */
|
|
668
|
+
const inFlight = new Set();
|
|
669
|
+
/** Whether any creation is still picking its CLI. */
|
|
670
|
+
export function creationsPending() {
|
|
671
|
+
return inFlight.size > 0;
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Creates a session in `folder` with `make` once its CLI is picked (#3640, #4157), registered under the chat `chatOf` names for the folder from the
|
|
675
|
+
* moment it is called, so an ask from that chat waits for it. A room DeepAgent could not read is written onto the session it makes, and that
|
|
676
|
+
* notice is handed back so a chat that started it hears it too.
|
|
677
|
+
*/
|
|
678
|
+
export function createdIn(folder, provider, chatOf, make) {
|
|
679
|
+
const creation = pickedCli(provider, folder).then((pick) => {
|
|
680
|
+
const made = make({ project: folder, provider: pick.provider });
|
|
681
|
+
// NULL-OK: field unreadBecause is OPTIONAL and therefore it is ok to check for NULL
|
|
682
|
+
if (pick.unreadBecause === undefined)
|
|
683
|
+
return { made };
|
|
684
|
+
const notice = appendEvent(made.id, { role: "system", kind: "status", ...(readEvents(made.id).some((e) => e.role === "user") ? { turn: 1 } : {}), text: `⚠️ No CLI was named, and DeepAgent's subscription room could not be read (${pick.unreadBecause}), so this runs on ${pick.provider}, the first subscription in the order.` });
|
|
685
|
+
return { made, notice };
|
|
686
|
+
});
|
|
687
|
+
inFlight.add(creation);
|
|
688
|
+
const chat = chatOf(folder);
|
|
689
|
+
// NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
|
|
690
|
+
const pending = chat === undefined ? new Set() : (creating.get(chat) ?? new Set());
|
|
691
|
+
pending.add(creation);
|
|
692
|
+
// NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
|
|
693
|
+
if (chat !== undefined)
|
|
694
|
+
creating.set(chat, pending);
|
|
695
|
+
return creation.finally(() => {
|
|
696
|
+
inFlight.delete(creation);
|
|
697
|
+
pending.delete(creation);
|
|
698
|
+
// NULL-OK: field chat is OPTIONAL and therefore it is ok to check for NULL
|
|
699
|
+
if (chat !== undefined && pending.size === 0 && creating.get(chat) === pending)
|
|
700
|
+
creating.delete(chat);
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
/** A session CREATED on the folder and the agent CLI its creation named or left out (#3640, #4157): see `createdIn`. */
|
|
704
|
+
export function createdOn(project, provider, chatOf, make) {
|
|
705
|
+
return createdIn(namedProject(project), provider, chatOf, make);
|
|
706
|
+
}
|
|
620
707
|
/**
|
|
621
708
|
* Refuses, in words, a conversation with no CLI of its own to open or stream (#3845, #3916): its record names an agent this gateway does not run.
|
|
622
709
|
*/
|
package/dist/gateway/mcpDoor.js
CHANGED
|
@@ -21,7 +21,7 @@ import { performance } from "perf_hooks";
|
|
|
21
21
|
import { z } from "zod";
|
|
22
22
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
23
23
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
24
|
-
import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects,
|
|
24
|
+
import { GatewayError, MAX_WAIT_SECONDS, archiveConversation, deleteConversation, describeConversation, lastEventNumber, listProjects, createdOn, creationPending, openConversation, readConversation, routeAsk, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, stampWaitReturn, startConversation, stopConversation, unarchiveConversation, waitForEvents, waitForTurn, workspaceRoot, allowedProjects, requireOwnCli, scopedConversation, namedWorkspace, } from "./conversations.js";
|
|
25
25
|
import { workspacesFile } from "../shared/webhost/workspaceList.js";
|
|
26
26
|
import { PROVIDER_NAMES } from "./providers.js";
|
|
27
27
|
import { iconsFor } from "./iconDoor.js";
|
|
@@ -90,7 +90,7 @@ function projectField(offer) {
|
|
|
90
90
|
}
|
|
91
91
|
const instructions = (offer) => `BullseyeNotify (BN) runs a Claude Code agent on this machine, with access to the user's files, git repositories, shell, MCP servers, skills and rules.
|
|
92
92
|
agent_prompt sends the user's request to that agent and returns its answer. It covers questions about the user's projects, files, code, builds and servers.
|
|
93
|
-
A NEW conversation needs no project: leave project out whatever the request is about, and the agent runs at the workspace root (${offer.under}), the folder holding every project, exactly as a VS Code window with no workspace would, loading each project's rules so it routes the request to the right project by itself — never choose a project for the user. Name a project only when the user names one: project is exactly one of ${offer.list}, never a path, and agent_projects lists them with their paths. provider is exactly one of ${PROVIDER_NAMES.join(", ")}
|
|
93
|
+
A NEW conversation needs no project: leave project out whatever the request is about, and the agent runs at the workspace root (${offer.under}), the folder holding every project, exactly as a VS Code window with no workspace would, loading each project's rules so it routes the request to the right project by itself — never choose a project for the user. Name a project only when the user names one: project is exactly one of ${offer.list}, never a path, and agent_projects lists them with their paths. provider is exactly one of ${PROVIDER_NAMES.join(", ")}; left out, it is the agent CLI whose subscription has room, by DeepAgent's provider_room, subscription before any key. A call that goes on with a conversation that already exists needs neither, because both were bound when it was created.
|
|
94
94
|
agent_open opens a conversation with no message and starts nothing: it takes project and provider as above, both optional, spends nothing and returns the id of a session to ask with agent_send and read with agent_wait. The folder of an existing conversation is switched with agent_project, which never starts a new agent and never makes a new conversation.
|
|
95
95
|
An agent that runs in a project works on that project: its own folder is the board it writes to, so work belonging to another project is never done from it — tell the user in one line which project the work belongs to, then start that project's own agent: agent_start with project naming the project and text carrying the request (agent_prompt with project for a quick answer), read its answer with agent_wait and relay it.
|
|
96
96
|
A request that changes a project is a Story, and the Story belongs on that project's own board: the agent of that project — this conversation's own agent when the work is this project's, the agent this conversation starts with agent_start as above when it belongs to another project — files it or joins it with the bullseye-backlog MCP server that project's folder declares, before any work is done on it. Once a Story is on the board the normal BB → FleetView workflow owns its execution and dispatches the subagents that run it, so BN stays free for the user's questions and follows the Story's progress on the board. A short read-only question or a status check is answered directly. Every agent respects the shared claim store, the one claims file this machine's doors write, so no Story is executed twice: the lane that works a Story claims it when that lane is dispatched, and a message that only names a Story — a question about it, a status check — claims nothing, so it never stands in the way of the lane that works it. The long task in the example below goes the same way: agent_start and agent_wait are how such a request is sent and read, and the Story it becomes is filed and run as above.
|
|
@@ -214,7 +214,7 @@ function buildServer(caller, base, offer) {
|
|
|
214
214
|
conversation: z.string().min(1).optional().describe("A 'conversation' id an earlier agent_prompt returned, to address that agent; without it the call goes on with this connection's current agent"),
|
|
215
215
|
new: z.boolean().optional().describe("true starts a fresh agent instead of going on with the current one; with a conversation named it is ignored, because that conversation is addressed as usual"),
|
|
216
216
|
project: projectField(offer).optional().describe(`The workspace of a NEW conversation: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never taken from the request text`),
|
|
217
|
-
provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the
|
|
217
|
+
provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the one whose subscription has room, picked by DeepAgent's provider_room subscription first`),
|
|
218
218
|
model: z.string().min(1).optional(),
|
|
219
219
|
}, ({ text, conversation, new: fresh, project, provider, model }) => act(async () => {
|
|
220
220
|
const call = randomUUID().slice(0, 8);
|
|
@@ -222,10 +222,15 @@ function buildServer(caller, base, offer) {
|
|
|
222
222
|
const arrival = arrivalOf(requestIdOf(), call);
|
|
223
223
|
process.stderr.write(`[agent-gateway] agent_prompt ${call} recv trace=${arrival.trace}\n`);
|
|
224
224
|
// NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
|
|
225
|
-
const
|
|
225
|
+
const routes = conversation === undefined && fresh !== true;
|
|
226
|
+
// NULL-OK: field pending is OPTIONAL and therefore it is ok to check for NULL
|
|
227
|
+
for (let pending = routes ? creationPending(caller) : undefined; pending !== undefined; pending = creationPending(caller))
|
|
228
|
+
await pending;
|
|
229
|
+
// NULL-OK: field conversation is OPTIONAL and therefore it is ok to check for NULL
|
|
230
|
+
const target = conversation !== undefined ? seen(conversation) : (routes ? routeAsk(caller, text)?.id : undefined);
|
|
226
231
|
// NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
|
|
227
232
|
const sent = target === undefined
|
|
228
|
-
? { id: startConversation({ platform: "mcp", technical: true, chat: caller,
|
|
233
|
+
? { id: (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, model, text, receivedMs: Math.round(performance.now() - arrived), arrival }))).made.id, turn: 1 }
|
|
229
234
|
: { id: seen(target), turn: sendToConversation(target, text, Math.round(performance.now() - arrived), arrival).n };
|
|
230
235
|
const { events, ended, turn } = await waitForTurn(sent.id, sent.turn, MAX_WAIT_SECONDS);
|
|
231
236
|
const meta = readConversation(sent.id);
|
|
@@ -252,15 +257,15 @@ function buildServer(caller, base, offer) {
|
|
|
252
257
|
return { ...head, stopped: true, waitedMs, events: others, after };
|
|
253
258
|
return { ...head, working: true, waitedMs, events: others, after, next: `call agent_wait with id="${sent.id}", after=${after}, wait=${MAX_WAIT_SECONDS} until an event of kind answer, failed or stopped arrives` };
|
|
254
259
|
}));
|
|
255
|
-
server.tool("agent_projects", `The project folders on this machine (the folders under ${offer.under}), each with its absolute path and whether it is a git repository.`, {}, () => act(() => listProjects(viewerNow())));
|
|
256
|
-
server.tool("agent_start", `Creates a new conversation AND submits text as its first task (turn 1) in one call, and returns {id, state} at once without waiting for the agent. The way to run a long or autonomous task: read its progress and answer with agent_wait {id, after:1, wait:${MAX_WAIT_SECONDS}}, again with the after each reply returned, until an event of kind answer or failed with turn 1, or of kind stopped, arrives. The task is already submitted, so do not also agent_send the same text, and do not call agent_start again for it — each call starts another agent on the task. agent_prompt sends and waits in one blocking call instead.`, { project: projectField(offer).optional().describe(`The workspace this conversation runs in: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never resolved from the text`), text: z.string().min(1).describe("The first task, submitted by this call itself"), provider: z.string().min(1).optional().describe(`The agent CLI this conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the
|
|
260
|
+
server.tool("agent_projects", `The project folders on this machine (the folders under ${offer.under}), each with its absolute path and whether it is a git repository. A new conversation need not name one: with no project it runs at ${offer.under} itself, the folder holding them all, and the rules of each project route the request to it.`, {}, () => act(() => listProjects(viewerNow())));
|
|
261
|
+
server.tool("agent_start", `Creates a new conversation AND submits text as its first task (turn 1) in one call, and returns {id, state} at once without waiting for the agent. The way to run a long or autonomous task: read its progress and answer with agent_wait {id, after:1, wait:${MAX_WAIT_SECONDS}}, again with the after each reply returned, until an event of kind answer or failed with turn 1, or of kind stopped, arrives. The task is already submitted, so do not also agent_send the same text, and do not call agent_start again for it — each call starts another agent on the task. agent_prompt sends and waits in one blocking call instead.`, { project: projectField(offer).optional().describe(`The workspace this conversation runs in: exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out and the conversation runs at the workspace root (${offer.under}) with every project's rules, which route the request to its project; it is never resolved from the text`), text: z.string().min(1).describe("The first task, submitted by this call itself"), provider: z.string().min(1).optional().describe(`The agent CLI this conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the one whose subscription has room, picked by DeepAgent's provider_room subscription first`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(async () => {
|
|
257
262
|
const arrived = performance.now();
|
|
258
263
|
const arrival = arrivalOf(requestIdOf(), randomUUID().slice(0, 8));
|
|
259
|
-
const meta = startConversation({ platform: "mcp", technical: true, chat: caller,
|
|
264
|
+
const meta = (await createdOn(project, provider, () => caller, (on) => startConversation({ platform: "mcp", technical: true, chat: caller, ...on, model, text, receivedMs: Math.round(performance.now() - arrived), arrival }))).made;
|
|
260
265
|
return { id: meta.id, state: meta.state };
|
|
261
266
|
}));
|
|
262
|
-
server.tool("agent_open", `Opens a new conversation with no message and starts no agent: no text, no process started and nothing spent. It returns {id, state} at once. It names the workspace and the agent CLI the conversation opens on — project and provider are both optional: a conversation with no project runs at the workspace root, whose rules route each request to its project, and one with no provider runs on the
|
|
263
|
-
const meta = openConversation({ platform: "mcp", technical: true, chat: caller,
|
|
267
|
+
server.tool("agent_open", `Opens a new conversation with no message and starts no agent: no text, no process started and nothing spent. It returns {id, state} at once. It names the workspace and the agent CLI the conversation opens on — project and provider are both optional: a conversation with no project runs at the workspace root, whose rules route each request to its project, and one with no provider runs on the agent CLI whose subscription has room. Ask it with agent_send and read it with agent_wait; the folder can be switched afterwards with agent_project, and the conversation keeps its id and its whole transcript.`, { project: projectField(offer).optional().describe(`Exactly one of ${offer.either}, resolved under ${offer.under}; no path is accepted. Leave it out for the workspace root (${offer.under}), where the rules of every project route the request; it is never resolved from anything else`), provider: z.string().min(1).optional().describe(`The agent CLI the conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Leave it out for the one whose subscription has room, picked by DeepAgent's provider_room subscription first`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(async () => {
|
|
268
|
+
const meta = (await createdOn(project, provider, () => caller, (on) => openConversation({ platform: "mcp", technical: true, chat: caller, ...on, model }))).made;
|
|
264
269
|
return { id: meta.id, state: meta.state };
|
|
265
270
|
}));
|
|
266
271
|
server.tool("agent_send", `Sends a message to a conversation that already exists (agent_start or agent_prompt made it) and returns {n} at once without waiting for the agent. n is the message's position in the log and the number of the turn it starts: read its answer with agent_wait {id, after:n, wait:${MAX_WAIT_SECONDS}}. A message sent while a turn runs is queued behind that turn, not an interrupt — also while a conversation's agent waits on a question on its own CLI screen, which the user answers there by opening the conversation in BN, never by a message to it. A stopped or archived conversation resumes. Each call submits its text once more, so do not repeat a send that returned.`, { id: z.string().min(1).describe("The conversation id agent_start returned, or the 'conversation' agent_prompt returned"), text: z.string().min(1).describe("The follow-up message; the first task belongs in agent_start") }, ({ id, text }) => act(() => {
|
|
@@ -324,7 +329,7 @@ function buildServer(caller, base, offer) {
|
|
|
324
329
|
server.tool("agent_archive", "Archive a conversation: it is stopped and moved off the default list to the Archived list with its transcript kept. agent_list archived=true shows it; a message to it (agent_send or agent_prompt) brings it back and resumes it.", { id: z.string().min(1), restore: z.boolean().default(false).describe("true moves an archived conversation back to the default list instead") }, ({ id, restore }) => act(() => (seen(id), restore ? unarchiveConversation(id) : archiveConversation(id))));
|
|
325
330
|
server.tool("agent_delete", "Delete a conversation for good: a running agent is stopped first, then the conversation and its transcript are removed from BN. It cannot be undone — agent_archive keeps the transcript instead.", { id: z.string().min(1) }, ({ id }) => act(() => deleteConversation(seen(id))));
|
|
326
331
|
server.tool("agent_terminals", "The agent CLIs this person has open on this machine (what the CLI page lists) with the CLIs New Agent can open and whether each takes a model; id names one terminal and answers only its facts. A read — it starts nothing.", { id: z.string().min(1).optional().describe("One terminal's conversation id; without it every open terminal is listed beside the CLIs New Agent offers") }, ({ id }) => act(async () => (id === undefined ? scopedListing(await terminalListing(personId())) : (seen(id), nativeTerminal(personId(), id).info()))));
|
|
327
|
-
server.tool("agent_terminal_open", `New Agent, as the CLI page's button runs it: opens a conversation's own agent CLI and sizes its screen. Name conversation to open the CLI of one that exists (agent_open or agent_start made it); otherwise a new empty conversation is made on project (exactly one of ${offer.either}, or none for the workspace root) and provider (one of ${PROVIDER_NAMES.join(", ")}, or none for the
|
|
332
|
+
server.tool("agent_terminal_open", `New Agent, as the CLI page's button runs it: opens a conversation's own agent CLI and sizes its screen. Name conversation to open the CLI of one that exists (agent_open or agent_start made it); otherwise a new empty conversation is made on project (exactly one of ${offer.either}, or none for the workspace root) and provider (one of ${PROVIDER_NAMES.join(", ")}, or none for the one whose subscription has room), with no turn and nothing spent.`, {
|
|
328
333
|
conversation: z.string().min(1).optional().describe("An existing conversation id whose own CLI to open"),
|
|
329
334
|
project: projectField(offer).optional(),
|
|
330
335
|
provider: z.string().min(1).optional(),
|
|
@@ -332,7 +337,7 @@ function buildServer(caller, base, offer) {
|
|
|
332
337
|
cols: z.number().int().min(1).max(1000).default(100),
|
|
333
338
|
rows: z.number().int().min(1).max(500).default(30),
|
|
334
339
|
}, (body) => act(() => { if (typeof body.conversation === "string")
|
|
335
|
-
seen(body.conversation.trim()); return openTerminal(body,
|
|
340
|
+
seen(body.conversation.trim()); return openTerminal(body, viewerNow()); }));
|
|
336
341
|
server.tool("agent_terminal_close", "Ends a terminal's CLI process, as the CLI page's Close does; the conversation and its transcript stay and a later message resumes it.", { id: z.string().min(1).describe("The terminal's conversation id") }, ({ id }) => act(() => closeNativeTerminal(personId(), seen(id))));
|
|
337
342
|
server.tool("agent_terminal_input", "Types raw keystrokes into a terminal's live CLI — what the CLI page sends for every key, answering a question the CLI waits on included. data is text; binary=true means data is base64 bytes. agent_send is the message door; this one is the keyboard.", { id: z.string().min(1), data: z.string().min(1), binary: z.boolean().default(false) }, ({ id, data, binary }) => act(async () => { seen(id); await nativeTerminal(personId(), id).input(data, binary); return { id, sent: true }; }));
|
|
338
343
|
server.tool("agent_terminal_resize", "Resizes a terminal's screen to whole columns 1-1000 and rows 1-500, as the CLI page does when its window changes.", { id: z.string().min(1), cols: z.number().int(), rows: z.number().int() }, ({ id, cols, rows }) => act(async () => { seen(id); const size = dimensions({ cols, rows }); await nativeTerminal(personId(), id).resize(size.cols, size.rows); return { id, ...size }; }));
|
package/dist/gateway/provider.js
CHANGED
|
@@ -7,8 +7,6 @@ export class AgentTurnFailed extends Error {
|
|
|
7
7
|
this.shown = shown;
|
|
8
8
|
}
|
|
9
9
|
}
|
|
10
|
-
/** The provider a conversation that names none runs on. */
|
|
11
|
-
export const DEFAULT_PROVIDER = "claude";
|
|
12
10
|
/**
|
|
13
11
|
* The environment every provider starts its CLI in (#2336): the daemon's own, with the project binding pinned to the
|
|
14
12
|
* folder the agent runs in. BN is ONE daemon on the machine, started by whichever window bound the gateway port first, so
|
package/dist/gateway/restDoor.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* once a passkey is enrolled the gateway token is honoured only on a request from this machine.
|
|
10
10
|
*/
|
|
11
11
|
import { createServer } from "http";
|
|
12
|
-
import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders,
|
|
12
|
+
import { GatewayError, archiveConversation, deleteConversation, listProjects, monotonicMs, scopedConversation, viewerOfHeaders, createdOn, creatorOf, openConversation, readConversation, requireConversationEnabled, sendToConversation, setConversationProject, shelvedConversations, startConversation, stopConversation, unarchiveConversation, waitForEvents, } from "./conversations.js";
|
|
13
13
|
import { CHAT_HEADERS } from "./chatPage.js";
|
|
14
14
|
import { isIconPath, serveIcon } from "./iconDoor.js";
|
|
15
15
|
import { handleMcp } from "./mcpDoor.js";
|
|
@@ -138,17 +138,16 @@ async function route(req, url, arrivedAt) {
|
|
|
138
138
|
return { status: 200, body: { conversations: shelvedConversations(shelfOf(url), viewer) } };
|
|
139
139
|
if (method === "POST") {
|
|
140
140
|
const body = await readJson(req);
|
|
141
|
-
const provider = namedProvider(body.provider);
|
|
142
141
|
const model = typeof body.model === "string" && body.model.length > 0 ? body.model : undefined;
|
|
143
|
-
const receivedMs = monotonicMs() - arrivedAt;
|
|
144
|
-
const project = namedProject(body.project);
|
|
145
142
|
// A text that is left out opens an empty conversation (#2723); one that is sent must carry something, so a blank text is still refused.
|
|
146
143
|
const text = body.text === undefined ? undefined : requiredText(body, "text");
|
|
147
|
-
// The workspace and the agent CLI are bound by this call (#3640): the text never resolves either; a call that names none runs at the workspace root on the
|
|
148
|
-
|
|
149
|
-
const meta =
|
|
150
|
-
|
|
151
|
-
|
|
144
|
+
// The workspace and the agent CLI are bound by this call (#3640): the text never resolves either; a call that names none runs at the workspace root on the CLI with subscription room (#4157).
|
|
145
|
+
let receivedMs = 0;
|
|
146
|
+
const { made: meta } = await createdOn(body.project, body.provider, (folder) => creatorOf(viewer, folder), (on) => {
|
|
147
|
+
receivedMs = monotonicMs() - arrivedAt;
|
|
148
|
+
const chat = creatorOf(viewer, on.project);
|
|
149
|
+
return text === undefined ? openConversation({ platform: "rest", chat, ...on, model }) : startConversation({ platform: "rest", chat, ...on, model, text, receivedMs });
|
|
150
|
+
});
|
|
152
151
|
return { status: 201, body: { id: meta.id, state: meta.state, receivedMs } };
|
|
153
152
|
}
|
|
154
153
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { WebSocketServer, WebSocket } from "ws";
|
|
2
|
-
import { GatewayError,
|
|
2
|
+
import { GatewayError, createdOn, creatorOf, deleteConversation, openConversation, requireOwnCli, requireConversationEnabled, scopedConversation, conversationInScope, viewerOfHeaders } from "./conversations.js";
|
|
3
3
|
import { closeNativeTerminal, consoleSession, nativeTerminal, nativeTerminals, terminalArriving } from "./nativeTerminal.js";
|
|
4
4
|
import { AgentGateway } from "../agentGateway.js";
|
|
5
5
|
import { bearer, bearerAdmitted, fromThisMachine, personId, sessionExpiresAt } from "./passkeyDoor.js";
|
|
@@ -182,12 +182,11 @@ export function nativeCatalog() {
|
|
|
182
182
|
return PROVIDER_NAMES.map((name) => providerFor(name)).map((provider) => ({ name: provider.name, label: provider.label, model: provider.nativeArgs !== undefined }));
|
|
183
183
|
}
|
|
184
184
|
/** The conversation New Agent makes: an empty one on the CLI and folder the form named, with no turn and nothing spent. */
|
|
185
|
-
function newAgent(body,
|
|
186
|
-
const provider = providerFor(namedProvider(body.provider));
|
|
185
|
+
async function newAgent(body, viewer) {
|
|
187
186
|
const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined;
|
|
188
187
|
if (model !== undefined && !/^[a-zA-Z0-9._:/-]+$/.test(model))
|
|
189
188
|
throw new GatewayError(400, "Model must be its CLI name, without spaces or shell characters.");
|
|
190
|
-
return openConversation({ platform: "rest", chat
|
|
189
|
+
return (await createdOn(body.project, body.provider, (folder) => creatorOf(viewer, folder), (on) => openConversation({ platform: "rest", chat: creatorOf(viewer, on.project), ...on, model }))).made.id;
|
|
191
190
|
}
|
|
192
191
|
/** The conversation's own CLI, opened by the session driver — never a second one — once it is running, or the reason this machine could not start it. */
|
|
193
192
|
async function opened(id) {
|
|
@@ -209,11 +208,11 @@ export async function terminalListing(owner) {
|
|
|
209
208
|
return { terminals: await nativeTerminals(owner), providers: nativeCatalog() };
|
|
210
209
|
}
|
|
211
210
|
/** New Agent, whole: a conversation made on the CLI and folder the body names (or the one it names), its own CLI opened and sized — what the page's New Agent and agent_terminal_open both run. */
|
|
212
|
-
export async function openTerminal(body,
|
|
213
|
-
// New Agent makes a conversation exactly as agent_open does —
|
|
214
|
-
//
|
|
211
|
+
export async function openTerminal(body, viewer) {
|
|
212
|
+
// New Agent makes a conversation exactly as agent_open does — on the CLI and the folder it names, or with none named at
|
|
213
|
+
// the workspace root on the CLI with subscription room (#4157) — and opens that conversation's own CLI, so a session the browser started and one MCP
|
|
215
214
|
// started are one kind: the same driven CLI, typed into by agent_send and shown here (#3916).
|
|
216
|
-
const terminal = typeof body.conversation === "string" && body.conversation.trim().length > 0 ? await opened(body.conversation.trim()) : await openedNew(newAgent(body,
|
|
215
|
+
const terminal = typeof body.conversation === "string" && body.conversation.trim().length > 0 ? await opened(body.conversation.trim()) : await openedNew(await newAgent(body, viewer));
|
|
217
216
|
const size = dimensions(body);
|
|
218
217
|
await terminal.resize(size.cols, size.rows);
|
|
219
218
|
return terminal.info();
|
|
@@ -233,7 +232,7 @@ export async function terminalRoute(req, url, readJson) {
|
|
|
233
232
|
const body = await readJson();
|
|
234
233
|
if (typeof body.conversation === "string" && viewer !== undefined)
|
|
235
234
|
scopedConversation(body.conversation.trim(), viewer);
|
|
236
|
-
return { status: 201, body: await openTerminal(body, viewer
|
|
235
|
+
return { status: 201, body: await openTerminal(body, viewer) };
|
|
237
236
|
}
|
|
238
237
|
}
|
|
239
238
|
if (viewer !== undefined)
|
|
@@ -181,8 +181,8 @@ async function newAgentView(){
|
|
|
181
181
|
var mine=show("new","New Agent");
|
|
182
182
|
var setup=el("div","setup"),provider=el("select"),project=el("select"),model=el("input"),open=el("button","go","▶ New Agent");
|
|
183
183
|
provider.setAttribute("aria-label","CLI provider");project.setAttribute("aria-label","Project");model.setAttribute("aria-label","Model");model.placeholder="Model (CLI default if empty)";
|
|
184
|
-
// Neither select forces a pick (#4157): no workspace runs the agent at the workspace root, where the rules of every project route each prompt, and no CLI runs the
|
|
185
|
-
var cliPlaceholder=el("option","","
|
|
184
|
+
// Neither select forces a pick (#4157): no workspace runs the agent at the workspace root, where the rules of every project route each prompt, and no CLI runs the one whose subscription has room.
|
|
185
|
+
var cliPlaceholder=el("option","","CLI with room (subscription first)"),folderPlaceholder=el("option","","Workspace root (any project)");
|
|
186
186
|
cliPlaceholder.value="";folderPlaceholder.value="";provider.append(cliPlaceholder);project.append(folderPlaceholder);
|
|
187
187
|
setup.append(provider,project,model,open);main.append(setup);
|
|
188
188
|
var folders=[],catalog=[];
|
|
@@ -192,7 +192,7 @@ async function newAgentView(){
|
|
|
192
192
|
open.disabled=catalog.length===0;
|
|
193
193
|
note.textContent=catalog.length===0
|
|
194
194
|
?"This gateway lists no CLI to run."
|
|
195
|
-
:"Starts a session with "+(chosen?(chosen.label||chosen.name):"the
|
|
195
|
+
:"Starts a session with "+(chosen?(chosen.label||chosen.name):"the CLI whose subscription has room")+" "+(project.value===""?"at the workspace root, where each prompt is routed to its project":"in "+project.value)+". Its conversation then opens in the same view.";
|
|
196
196
|
}
|
|
197
197
|
try{var listed=await api("GET","/v1/projects");if(mine!==view)return;folders=listed.projects.filter(function(p){return p.board;});folders.forEach(function(p){var option=el("option","",p.name);option.value=p.name;project.append(option);});
|
|
198
198
|
var sessions=await api("GET","/v1/terminals");if(mine!==view)return;
|
|
@@ -2006,7 +2006,7 @@ export function newerVersion(a, b) {
|
|
|
2006
2006
|
/** 🔴 #4156 — a move named an entry that is no longer in line on the board: withdrawn, finished or failed out between the press and the queue's lock. */
|
|
2007
2007
|
export class NotInQueue extends Error {
|
|
2008
2008
|
constructor(board, storyId) {
|
|
2009
|
-
super(`#${storyId} is
|
|
2009
|
+
super(`#${storyId} is no longer in FleetView's queue on ${board}`);
|
|
2010
2010
|
this.name = "NotInQueue";
|
|
2011
2011
|
}
|
|
2012
2012
|
}
|
|
@@ -2172,6 +2172,9 @@ export class WorkerNotStarted extends Error {
|
|
|
2172
2172
|
this.name = "WorkerNotStarted";
|
|
2173
2173
|
}
|
|
2174
2174
|
}
|
|
2175
|
+
/** 🔴 #4142 — a wake found the session still running: Claude Code started a copy of it, which took the message and was stopped, so the session's own process never received it. */
|
|
2176
|
+
export class SessionStillRunning extends WorkerNotStarted {
|
|
2177
|
+
}
|
|
2175
2178
|
/** 🔴 #3951 — the provider cannot start the story as this box stands (its CLI has no login): the entry stops `failed` with the provider's words at once, spends no attempt, and the box is read again after {@link RETRY_BASE_MS}, so a login made later starts it. */
|
|
2176
2179
|
export class WorkerRefused extends WorkerNotStarted {
|
|
2177
2180
|
retried = false;
|
|
@@ -2186,6 +2189,10 @@ export const WAKE_BASE_MS = 60_000;
|
|
|
2186
2189
|
export const WAKE_DOUBLINGS = 5;
|
|
2187
2190
|
/** 🔴 #4123 — how long after its turn ended a worker woken `wakes` times before is woken again. */
|
|
2188
2191
|
export const wakeDelayMs = (wakes) => WAKE_BASE_MS * 2 ** Math.min(wakes, WAKE_DOUBLINGS);
|
|
2192
|
+
/** 🔴 #4162 — its process was killed mid-work and its session went on working past its start grace after its last start or wake: nothing ended its turn and nothing of its own failed, so it neither backs off nor spends a start (#4164). */
|
|
2193
|
+
const killedAfterWork = (worker, parked) => parked.killed === true && worker.progressAt !== undefined && worker.progressAt - worker.startedAt >= WORKER_START_GRACE_MS;
|
|
2194
|
+
/** 🔴 #4162 — how long a parked worker waits before it is woken: none when {@link killedAfterWork}, else {@link wakeDelayMs} — so a session that dies on waking, whose only write is the wake's own message, still backs off and never wakes in a loop. */
|
|
2195
|
+
export const parkedWaitMs = (worker, parked) => (killedAfterWork(worker, parked) ? 0 : wakeDelayMs(worker.wakes ?? 0));
|
|
2189
2196
|
/** 🔴 #4123 — where every queue worker stands, said at its start and at each wake: what it clears itself, and how a decision of Meni's reaches him and comes back. */
|
|
2190
2197
|
const workerStanding = (storyId) => `A stop you named that you or another agent can clear (a board write refused, the board MCP not loaded yet, a release step) is yours to clear now — never a reason to end your turn. A run the box's CPU ceiling refuses is handled as its refusal says; never stop or kill a process to make room.
|
|
2191
2198
|
If a decision only Meni can make stands in the way, record it on #${storyId} with bullseye-backlog \`ask\` and ask him with the notify MCP \`ask\` tool, which reaches his email and text; when its wait ends unanswered, keep calling \`wait_for_inbox\` until his reply arrives, then \`rule\` his answer onto #${storyId} verbatim, apply it and go on. End your turn only once the story is shipped.`;
|
|
@@ -2482,7 +2489,7 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2482
2489
|
delete e.worker.needs;
|
|
2483
2490
|
else
|
|
2484
2491
|
e.worker.needs = w.needs;
|
|
2485
|
-
e.why = `its ${e.provider} worker ${e.worker.jobId} stopped and needs an act before it goes on: ${blockedAct(e.worker)}`;
|
|
2492
|
+
e.why = `its ${e.worker.provider} worker ${e.worker.jobId} stopped and needs an act before it goes on: ${blockedAct(e.worker)}`;
|
|
2486
2493
|
step(e, now, "blocked", e.why);
|
|
2487
2494
|
}
|
|
2488
2495
|
else {
|
|
@@ -2508,14 +2515,14 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2508
2515
|
}
|
|
2509
2516
|
const worker = e.worker;
|
|
2510
2517
|
if (!e.eligible) {
|
|
2511
|
-
const why = `its ${
|
|
2518
|
+
const why = `its ${worker.provider} worker ${worker.jobId}'s turn is over and the story is no longer the queue's to work, so it is not woken`;
|
|
2512
2519
|
step(e, now, "worker-ended", why);
|
|
2513
2520
|
afterWorker(e, now, why);
|
|
2514
2521
|
idle = idleWorker(worker, () => w, now);
|
|
2515
2522
|
break judge;
|
|
2516
2523
|
}
|
|
2517
2524
|
// NULL-OK: field parkedAt is OPTIONAL and therefore it is ok to check for NULL
|
|
2518
|
-
if (worker.parkedAt === undefined && w.parked.failed === true) {
|
|
2525
|
+
if (worker.parkedAt === undefined && w.parked.failed === true && !killedAfterWork(worker, w.parked)) {
|
|
2519
2526
|
if (e.attempts >= WORKER_ATTEMPTS) {
|
|
2520
2527
|
idle = idleWorker(worker, () => w, now);
|
|
2521
2528
|
delete e.worker;
|
|
@@ -2528,10 +2535,10 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2528
2535
|
// NULL-OK: field parkedAt is OPTIONAL and therefore it is ok to check for NULL
|
|
2529
2536
|
if (worker.parkedAt === undefined) {
|
|
2530
2537
|
worker.parkedAt = now;
|
|
2531
|
-
step(e, now, "parked", `its ${
|
|
2538
|
+
step(e, now, "parked", `its ${worker.provider} worker ${worker.jobId}'s turn is over with the story open, so it is woken in its own session from ${new Date(now + parkedWaitMs(worker, w.parked)).toISOString()}`);
|
|
2532
2539
|
}
|
|
2533
2540
|
if (!w.parked.live) {
|
|
2534
|
-
if (now >= worker.parkedAt +
|
|
2541
|
+
if (now >= worker.parkedAt + parkedWaitMs(worker, w.parked))
|
|
2535
2542
|
wakeable.set(e, w.parked.sessionId);
|
|
2536
2543
|
continue;
|
|
2537
2544
|
}
|
|
@@ -2594,6 +2601,8 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2594
2601
|
}
|
|
2595
2602
|
}
|
|
2596
2603
|
save();
|
|
2604
|
+
// NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
|
|
2605
|
+
const halted = store.stopped === undefined ? undefined : `the queue is stopped (${store.stopped.by}), so nothing more starts or wakes until ▶ Run`;
|
|
2597
2606
|
let lanes = world.lanesRunning();
|
|
2598
2607
|
for (const e of queueOrder(store)) {
|
|
2599
2608
|
const sessionId = wakeable.get(e);
|
|
@@ -2606,6 +2615,11 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2606
2615
|
e.why = `${held} works it, so its parked worker ${parked.jobId} is not woken beside it`;
|
|
2607
2616
|
continue;
|
|
2608
2617
|
}
|
|
2618
|
+
// NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
|
|
2619
|
+
if (halted !== undefined) {
|
|
2620
|
+
e.why = `its worker ${parked.jobId} is parked, and ${halted}`;
|
|
2621
|
+
continue;
|
|
2622
|
+
}
|
|
2609
2623
|
if (lanes >= world.limit) {
|
|
2610
2624
|
e.why = `its worker ${parked.jobId} is parked, and ${lanes} lanes run with the lane limit at ${world.limit}, so it is woken when one finishes`;
|
|
2611
2625
|
continue;
|
|
@@ -2621,6 +2635,15 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2621
2635
|
catch (err) {
|
|
2622
2636
|
if (!(err instanceof WorkerNotStarted))
|
|
2623
2637
|
throw err;
|
|
2638
|
+
if (err instanceof SessionStillRunning) {
|
|
2639
|
+
// OWNER: ITER/LOOP — the session still ran when it was woken, so Claude Code started a copy, which took the message and was stopped: the session's own process never got it, so the worker stays parked and is stopped and woken again; the next entry is read.
|
|
2640
|
+
lanes -= 1;
|
|
2641
|
+
e.worker = { ...parked, startedAt: now, parkedAt: now, wakes };
|
|
2642
|
+
e.why = `its worker ${parked.jobId} was NOT woken: ${err.message}`;
|
|
2643
|
+
step(e, now, "parked", e.why);
|
|
2644
|
+
save();
|
|
2645
|
+
continue;
|
|
2646
|
+
}
|
|
2624
2647
|
const after = world.worker(e, board);
|
|
2625
2648
|
// NULL-OK: field parked is OPTIONAL and therefore it is ok to check for NULL
|
|
2626
2649
|
if (after.alive && (after.parked === undefined || after.parked.live)) {
|
|
@@ -2632,14 +2655,14 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2632
2655
|
else if (!err.unsent) {
|
|
2633
2656
|
// OWNER: ITER/LOOP — the wake's answer was lost and no process has recorded the session yet, so the worker stays parked and is read again next pass; it is never ended on a missing answer, which would start a second worker beside a wake that landed late; the next entry is read.
|
|
2634
2657
|
lanes -= 1;
|
|
2635
|
-
e.worker = { ...parked, parkedAt: now, wakes };
|
|
2658
|
+
e.worker = { ...parked, startedAt: now, parkedAt: now, wakes };
|
|
2636
2659
|
e.why = `its worker ${parked.jobId}'s wake got no answer, so it stays parked and is read again: ${err.message}`;
|
|
2637
2660
|
step(e, now, "parked", e.why);
|
|
2638
2661
|
}
|
|
2639
2662
|
else {
|
|
2640
2663
|
// OWNER: ITER/LOOP — Claude Code refused to wake this story's session and no process runs it, so the worker has ended: its entry carries the provider's words and a fresh worker is started on its backoff; the next entry is read.
|
|
2641
2664
|
lanes -= 1;
|
|
2642
|
-
const why = `its ${
|
|
2665
|
+
const why = `its ${parked.provider} worker ${parked.jobId} could not be woken: ${err.message}`;
|
|
2643
2666
|
delete e.worker;
|
|
2644
2667
|
step(e, now, "worker-ended", why);
|
|
2645
2668
|
afterWorker(e, now, why);
|
|
@@ -2662,21 +2685,35 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2662
2685
|
e.why = `${held} works it, so the queue starts no second worker`;
|
|
2663
2686
|
continue;
|
|
2664
2687
|
}
|
|
2665
|
-
|
|
2688
|
+
// NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
|
|
2689
|
+
if (halted !== undefined && e.forced !== true) {
|
|
2690
|
+
e.why = halted;
|
|
2691
|
+
continue;
|
|
2692
|
+
}
|
|
2693
|
+
if (lanes >= world.limit && e.forced !== true) {
|
|
2666
2694
|
e.why = `${lanes} lanes run and the lane limit is ${world.limit}, so it starts when one finishes`;
|
|
2667
2695
|
continue;
|
|
2668
2696
|
}
|
|
2669
2697
|
// NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
|
|
2670
2698
|
if (e.worker !== undefined && world.worker(e, board).alive) {
|
|
2699
|
+
delete e.forced;
|
|
2671
2700
|
e.state = "running";
|
|
2672
2701
|
e.why = `its ${e.worker.provider} worker ${e.worker.jobId} still runs, so no second worker is started`;
|
|
2673
2702
|
step(e, now, "started", e.why);
|
|
2674
2703
|
continue;
|
|
2675
2704
|
}
|
|
2705
|
+
const taken = world.seat(e);
|
|
2706
|
+
if (taken !== undefined) {
|
|
2707
|
+
e.why = `${taken} works it, so the queue starts no second worker`;
|
|
2708
|
+
continue;
|
|
2709
|
+
}
|
|
2710
|
+
// NULL-OK: field halted is OPTIONAL and therefore it is ok to check for NULL
|
|
2711
|
+
const forced = e.forced === true && (halted !== undefined || lanes >= world.limit);
|
|
2712
|
+
delete e.forced;
|
|
2676
2713
|
e.state = "starting";
|
|
2677
2714
|
e.attempts += 1;
|
|
2678
2715
|
delete e.worker;
|
|
2679
|
-
step(e, now, "selected", `start ${e.attempts}${e.attempts > WORKER_ATTEMPTS ? ", past the attempts a story is given" : ` of ${WORKER_ATTEMPTS}`}, with ${lanes} of ${world.limit} lanes running`);
|
|
2716
|
+
step(e, now, "selected", `start ${e.attempts}${e.attempts > WORKER_ATTEMPTS ? ", past the attempts a story is given" : ` of ${WORKER_ATTEMPTS}`}, with ${lanes} of ${world.limit} lanes running${forced ? ` — his ⚡ Force start, past ${halted === undefined ? "the lane limit" : "the queue's ⏸ Stop"}` : ""}`);
|
|
2680
2717
|
save();
|
|
2681
2718
|
lanes += 1;
|
|
2682
2719
|
try {
|
|
@@ -2714,6 +2751,101 @@ export async function driveStoryQueue(board, world, now) {
|
|
|
2714
2751
|
return store;
|
|
2715
2752
|
});
|
|
2716
2753
|
}
|
|
2754
|
+
/** 🔴 #4156 — a press on one story of the queue that does not apply to it as it stands: the words say why and what it reads. */
|
|
2755
|
+
export class StoryPressRefused extends Error {
|
|
2756
|
+
constructor(message) {
|
|
2757
|
+
super(message);
|
|
2758
|
+
this.name = "StoryPressRefused";
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
/**
|
|
2762
|
+
* 🔴 #4156 — HIS PRESS ON ONE STORY OF FLEETVIEW'S QUEUE, under the queue's lock: ✕ Remove takes it out of the line (BullseyeBacklog's
|
|
2763
|
+
* next new request puts it back), ↻ Retry puts a failed or retrying story back in line with its attempts reset, ⚡ Force start starts
|
|
2764
|
+
* it on the next pass past the lane limit and a ⏸ Stop, 🔔 Nudge ends the wait it stands on (a retry's backoff, a parked worker's wake delay), and
|
|
2765
|
+
* 🔓 Unblock answers what holds it — the queue keeps no hold of its own on a story. A press that does not apply throws
|
|
2766
|
+
* {@link StoryPressRefused}; one on a story no longer in line throws {@link NotInQueue}. Answers what it did, in words.
|
|
2767
|
+
*/
|
|
2768
|
+
export async function pressStory(board, storyId, press, now) {
|
|
2769
|
+
return withQueueLock(board, now, async () => {
|
|
2770
|
+
const store = readQueueStore(board);
|
|
2771
|
+
const e = store.entries.find((x) => x.storyId === storyId && IN_LINE.has(x.state));
|
|
2772
|
+
if (e === undefined)
|
|
2773
|
+
throw new NotInQueue(board, storyId);
|
|
2774
|
+
const working = e.state === "starting" || e.state === "running";
|
|
2775
|
+
// NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
|
|
2776
|
+
const afterStop = store.stopped === undefined ? "" : " after ▶ Run lifts the queue's ⏸ Stop";
|
|
2777
|
+
let did;
|
|
2778
|
+
if (press === "remove") {
|
|
2779
|
+
if (working)
|
|
2780
|
+
throw new StoryPressRefused(`#${storyId} has a worker at work — ✕ Remove takes a waiting story out of the line, and ⛔ Kill on its lane stops a worker`);
|
|
2781
|
+
e.state = "withdrawn";
|
|
2782
|
+
delete e.forced;
|
|
2783
|
+
e.why = "his ✕ Remove took it out of the line — BullseyeBacklog's next new request for it puts it back";
|
|
2784
|
+
step(e, now, "withdrawn", e.why);
|
|
2785
|
+
did = `#${storyId} is out of the line`;
|
|
2786
|
+
}
|
|
2787
|
+
else if (press === "retry") {
|
|
2788
|
+
if (e.state !== "failed" && e.state !== "retrying")
|
|
2789
|
+
throw new StoryPressRefused(`#${storyId} is ${e.state}, and ↻ Retry puts back only a failed or retrying story`);
|
|
2790
|
+
e.state = "queued";
|
|
2791
|
+
e.attempts = 0;
|
|
2792
|
+
delete e.nextTryAt;
|
|
2793
|
+
e.why = "his ↻ Retry put it back in line with its attempts reset";
|
|
2794
|
+
step(e, now, "retry", e.why);
|
|
2795
|
+
did = `#${storyId} is back in line`;
|
|
2796
|
+
}
|
|
2797
|
+
else if (press === "force") {
|
|
2798
|
+
if (working)
|
|
2799
|
+
throw new StoryPressRefused(`#${storyId} already has a worker at work, so there is nothing to force`);
|
|
2800
|
+
e.state = "queued";
|
|
2801
|
+
delete e.nextTryAt;
|
|
2802
|
+
e.forced = true;
|
|
2803
|
+
e.why = "his ⚡ Force start starts it on the next pass, past the lane limit and a ⏸ Stop";
|
|
2804
|
+
step(e, now, "placed", e.why);
|
|
2805
|
+
did = `#${storyId} starts on the next pass, past the lane limit`;
|
|
2806
|
+
}
|
|
2807
|
+
else if (press === "nudge") {
|
|
2808
|
+
const parked = e.state === "running" ? e.worker : undefined;
|
|
2809
|
+
// NULL-OK: field parkedAt is OPTIONAL and therefore it is ok to check for NULL
|
|
2810
|
+
if (parked?.parkedAt !== undefined) {
|
|
2811
|
+
parked.parkedAt = now - wakeDelayMs(parked.wakes ?? 0);
|
|
2812
|
+
e.why = `his 🔔 Nudge ended its parked worker ${parked.jobId}'s wake delay, so it is woken on the next pass${afterStop}`;
|
|
2813
|
+
did = `#${storyId}'s worker is woken on the next pass${afterStop}`;
|
|
2814
|
+
// NULL-OK: field nextTryAt is OPTIONAL and therefore it is ok to check for NULL
|
|
2815
|
+
}
|
|
2816
|
+
else if (e.nextTryAt !== undefined && e.nextTryAt > now) {
|
|
2817
|
+
e.nextTryAt = now;
|
|
2818
|
+
e.why = `his 🔔 Nudge ended its wait, so it is tried on the next pass${afterStop}`;
|
|
2819
|
+
did = `#${storyId} is tried on the next pass${afterStop}`;
|
|
2820
|
+
}
|
|
2821
|
+
else {
|
|
2822
|
+
throw new StoryPressRefused(`#${storyId} waits on nothing a nudge ends — it reads: ${e.why}${e.state === "queued" ? "; ⚡ Force start runs it past the lane limit" : ""}`);
|
|
2823
|
+
}
|
|
2824
|
+
step(e, now, "retry", e.why);
|
|
2825
|
+
}
|
|
2826
|
+
else {
|
|
2827
|
+
throw new StoryPressRefused(`#${storyId} carries no hold — FleetView's queue keeps none of its own on a story; it reads: ${e.why}`);
|
|
2828
|
+
}
|
|
2829
|
+
writeWhole(board, storeFile(board), store);
|
|
2830
|
+
writeAcks(board, store, new Map(), new Map([[e.storyId, e.requestId]]), now);
|
|
2831
|
+
return did;
|
|
2832
|
+
});
|
|
2833
|
+
}
|
|
2834
|
+
/** 🔴 #4156 — his ▶ Run or ⏸ Stop on the board's queue: stopped, nothing more starts or wakes until he runs it again; workers already running carry on. Answers whether it changed. */
|
|
2835
|
+
export async function setStoryQueueStopped(board, stopped, by, now) {
|
|
2836
|
+
return withQueueLock(board, now, async () => {
|
|
2837
|
+
const store = readQueueStore(board);
|
|
2838
|
+
// NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
|
|
2839
|
+
if ((store.stopped !== undefined) === stopped)
|
|
2840
|
+
return false;
|
|
2841
|
+
if (stopped)
|
|
2842
|
+
store.stopped = { at: now, by };
|
|
2843
|
+
else
|
|
2844
|
+
delete store.stopped;
|
|
2845
|
+
writeWhole(board, storeFile(board), store);
|
|
2846
|
+
return true;
|
|
2847
|
+
});
|
|
2848
|
+
}
|
|
2717
2849
|
/** His placement of one story in FleetView's queue: a 0-based place, or `auto` to hand it back to priority and size. */
|
|
2718
2850
|
export async function placeStory(board, storyId, place, now) {
|
|
2719
2851
|
return withQueueLock(board, now, async () => {
|
|
@@ -2730,6 +2862,37 @@ export async function placeStory(board, storyId, place, now) {
|
|
|
2730
2862
|
return e;
|
|
2731
2863
|
});
|
|
2732
2864
|
}
|
|
2865
|
+
/** 🔴 #4154 — FleetView's investigator ruled ABORT on the worker `jobId` of this story: its entry leaves the line, so the stopped worker is never woken, and his next Start press brings the story back; undefined when no entry in line runs that worker. */
|
|
2866
|
+
export async function withdrawStory(board, storyId, jobId, why, now) {
|
|
2867
|
+
return withQueueLock(board, now, async () => {
|
|
2868
|
+
const store = readQueueStore(board);
|
|
2869
|
+
const e = store.entries.find((x) => x.storyId === storyId && IN_LINE.has(x.state) && x.worker?.jobId === jobId);
|
|
2870
|
+
if (e === undefined)
|
|
2871
|
+
return undefined;
|
|
2872
|
+
e.state = "withdrawn";
|
|
2873
|
+
e.why = why;
|
|
2874
|
+
step(e, now, "withdrawn", why);
|
|
2875
|
+
writeWhole(board, storeFile(board), store);
|
|
2876
|
+
return e;
|
|
2877
|
+
});
|
|
2878
|
+
}
|
|
2879
|
+
/** 🔴 #4154 — a decision's message put to the queue's own worker `jobId` of this story: the job is stopped and woken in its own session with the message, and the entry carries the woken job, so the queue never reads it as ended and starts a second worker; undefined when no entry in line runs that worker. */
|
|
2880
|
+
export async function rewakeStoryWorker(board, storyId, jobId, sessionId, message, cli, now) {
|
|
2881
|
+
return withQueueLock(board, now, async () => {
|
|
2882
|
+
const store = readQueueStore(board);
|
|
2883
|
+
const e = store.entries.find((x) => x.storyId === storyId && IN_LINE.has(x.state) && x.worker?.jobId === jobId);
|
|
2884
|
+
if (e === undefined)
|
|
2885
|
+
return undefined;
|
|
2886
|
+
const parked = e.worker;
|
|
2887
|
+
await stopStoryWorker(jobId, cli);
|
|
2888
|
+
const woken = await wakeStoryWorker(sessionId, message, board, cli, now);
|
|
2889
|
+
e.worker = { ...woken, wakes: (parked.wakes ?? 0) + 1, ...keptSession(parked) };
|
|
2890
|
+
e.why = `FleetView's investigator redirected its worker ${jobId}, woken in its own session as ${woken.jobId}`;
|
|
2891
|
+
step(e, now, "woken", e.why);
|
|
2892
|
+
writeWhole(board, storeFile(board), store);
|
|
2893
|
+
return woken;
|
|
2894
|
+
});
|
|
2895
|
+
}
|
|
2733
2896
|
const claudeHome = () => process.env.CLAUDE_CONFIG_DIR ?? path.join(homedir(), ".claude");
|
|
2734
2897
|
/** A Claude Code record: its JSON, `gone` when Claude Code has none there (deleted, or an entry that is not a record), or `torn` when it was read mid-rewrite — Claude Code rewrites and deletes them in place. */
|
|
2735
2898
|
function claudeRecordOf(file) {
|
|
@@ -2785,6 +2948,19 @@ export function claudeJobsOfStory(storyId, board, since, home = claudeHome()) {
|
|
|
2785
2948
|
});
|
|
2786
2949
|
return jobs.filter((j) => j.at >= since).sort((a, b) => a.at - b.at).map((j) => j.id);
|
|
2787
2950
|
}
|
|
2951
|
+
/** 🔴 #4143 — the jobs, in any folder, whose brief opens with the same `Stories: #N — <title>` line as `brief`: a story's job started in a worktree or a nested repo, which {@link claudeJobsOfStory} never finds in the board's folder, is still that story's. */
|
|
2952
|
+
export function claudeJobsBriefed(brief, home = claudeHome()) {
|
|
2953
|
+
const dir = path.join(home, "jobs");
|
|
2954
|
+
if (!fs.existsSync(dir))
|
|
2955
|
+
return [];
|
|
2956
|
+
const first = brief.split("\n")[0];
|
|
2957
|
+
if (!/^Stories: #\d+ — \S/.test(first))
|
|
2958
|
+
return [];
|
|
2959
|
+
return fs.readdirSync(dir).filter((id) => {
|
|
2960
|
+
const job = jobRecordOf(id, home);
|
|
2961
|
+
return typeof job !== "string" && job.intent.split("\n")[0] === first;
|
|
2962
|
+
});
|
|
2963
|
+
}
|
|
2788
2964
|
// GATE: how long a just-started worker is read as alive before its process has written its own live record (1.4 s measured on HP)
|
|
2789
2965
|
export const WORKER_START_GRACE_MS = 2 * 60_000;
|
|
2790
2966
|
const mtimeOf = (file) => {
|
|
@@ -2810,7 +2986,59 @@ function goneWorker(worker, now, home) {
|
|
|
2810
2986
|
return { alive: true, why: `${gone}, and a process runs its session ${worker.session.id}, so it is still this story's worker` };
|
|
2811
2987
|
if (now - worker.startedAt < WORKER_START_GRACE_MS)
|
|
2812
2988
|
return { alive: true, why: `${gone}, and it was started ${Math.round((now - worker.startedAt) / 1000)}s ago, so its process may not have recorded its session ${worker.session.id} yet` };
|
|
2813
|
-
|
|
2989
|
+
const cut = turnCutOff(worker.session.transcript);
|
|
2990
|
+
return { alive: true, parked: { sessionId: worker.session.id, live: false, ...(cut ? { killed: true } : {}) }, why: `${gone} — its session ${worker.session.id} is on disk and no process runs it${cut ? ", and its last turn was cut off mid-work" : ""}, so it is parked and woken there` };
|
|
2991
|
+
}
|
|
2992
|
+
// GATE: how many bytes of a transcript one backward read takes while it looks for the last assistant record — the reads go on to the file's start, so nothing is ever left unread
|
|
2993
|
+
const TRANSCRIPT_READ_BYTES = 64 * 1024;
|
|
2994
|
+
/**
|
|
2995
|
+
* 🔴 #4162 — whether a session's last assistant record stopped on a tool call (`stop_reason: "tool_use"`) it never saw answered: its process was
|
|
2996
|
+
* killed mid-work. Read backward from the end, a block at a time, so a session of tens of megabytes costs one block on a beat; a line cut at a
|
|
2997
|
+
* block's start is carried into the next read, and the last line Claude Code is still appending says nothing yet.
|
|
2998
|
+
*/
|
|
2999
|
+
function turnCutOff(transcript) {
|
|
3000
|
+
const fd = fs.openSync(transcript, "r");
|
|
3001
|
+
try {
|
|
3002
|
+
let at = fs.fstatSync(fd).size;
|
|
3003
|
+
let carry = Buffer.alloc(0);
|
|
3004
|
+
while (at > 0) {
|
|
3005
|
+
const length = Math.min(at, TRANSCRIPT_READ_BYTES);
|
|
3006
|
+
at -= length;
|
|
3007
|
+
const block = Buffer.alloc(length);
|
|
3008
|
+
fs.readSync(fd, block, 0, length, at);
|
|
3009
|
+
const text = Buffer.concat([block, carry]);
|
|
3010
|
+
const first = text.indexOf(0x0a);
|
|
3011
|
+
carry = at > 0 && first >= 0 ? text.subarray(0, first) : at > 0 ? text : Buffer.alloc(0);
|
|
3012
|
+
const whole = at > 0 ? (first >= 0 ? text.subarray(first + 1) : Buffer.alloc(0)) : text;
|
|
3013
|
+
const stop = lastAssistantStop(whole.toString("utf8"));
|
|
3014
|
+
if (stop !== "none")
|
|
3015
|
+
return stop === "tool_use";
|
|
3016
|
+
}
|
|
3017
|
+
return false;
|
|
3018
|
+
}
|
|
3019
|
+
finally {
|
|
3020
|
+
fs.closeSync(fd);
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
/** The stop reason of the last whole assistant record in `lines`, its absence as "absent", or "none" when no assistant record is in them. */
|
|
3024
|
+
function lastAssistantStop(lines) {
|
|
3025
|
+
for (const line of lines.split("\n").reverse()) {
|
|
3026
|
+
if (!line.includes('"type":"assistant"'))
|
|
3027
|
+
continue;
|
|
3028
|
+
let record;
|
|
3029
|
+
try {
|
|
3030
|
+
record = JSON.parse(line);
|
|
3031
|
+
}
|
|
3032
|
+
catch (err) {
|
|
3033
|
+
if (!(err instanceof SyntaxError))
|
|
3034
|
+
throw err;
|
|
3035
|
+
// OWNER: ITER/LOOP — Claude Code is mid-append to its last line: that line says nothing yet, and the one before it is read.
|
|
3036
|
+
continue;
|
|
3037
|
+
}
|
|
3038
|
+
if (record.type === "assistant")
|
|
3039
|
+
return String(record.message.stop_reason ?? "absent");
|
|
3040
|
+
}
|
|
3041
|
+
return "none";
|
|
2814
3042
|
}
|
|
2815
3043
|
/** 🔴 #4123 — a job's last whole timeline step, which ends `failed` for a provider's refusal and mid-work for a job killed with the daemon, and whether a step after it is caught mid-append. */
|
|
2816
3044
|
function lastTimelineStep(jobId, home) {
|
|
@@ -2880,7 +3108,7 @@ export function storyWorkerLiveness(worker, now, home = claudeHome()) {
|
|
|
2880
3108
|
return { alive: true, ...progress, why: `${said} — its timeline's last step is still being written by its running process, so it is read again on the next pass` };
|
|
2881
3109
|
if (step.state === "failed" || at === undefined || at <= worker.startedAt)
|
|
2882
3110
|
return { alive: false, ...progress, why: said };
|
|
2883
|
-
return { alive: true, ...progress, parked: { sessionId: job.sessionId, live, failed: true }, why: `${said} — it was killed mid-work and its session worked after it was started, so it is parked and woken there` };
|
|
3111
|
+
return { alive: true, ...progress, parked: { sessionId: job.sessionId, live, failed: true, ...(live ? {} : { killed: true }) }, why: `${said} — it was killed mid-work and its session worked after it was started, so it is parked and woken there` };
|
|
2884
3112
|
}
|
|
2885
3113
|
// NULL-OK: field inFlight is OPTIONAL and therefore it is ok to check for NULL
|
|
2886
3114
|
const waitsOnTasks = job.inFlight !== undefined && job.inFlight.tasks + job.inFlight.queued + job.inFlight.drainableMonitors > 0;
|
|
@@ -2889,14 +3117,24 @@ export function storyWorkerLiveness(worker, now, home = claudeHome()) {
|
|
|
2889
3117
|
if (live && (!TURN_OVER.has(job.state) || waitsOnTasks))
|
|
2890
3118
|
return { alive: true, ...progress, why: `its job ${worker.jobId} runs as session ${job.sessionId} (${job.state})` };
|
|
2891
3119
|
const how = live ? `its turn ended ${job.state} and its process waits at the prompt` : `it reads ${job.state} and no process on this machine runs session ${job.sessionId}`;
|
|
2892
|
-
return { alive: true, ...progress, ...blocked, parked: { sessionId: job.sessionId, live }, why: `its job ${worker.jobId} is parked — ${how}` };
|
|
3120
|
+
return { alive: true, ...progress, ...blocked, parked: { sessionId: job.sessionId, live, ...(!live && !TURN_OVER.has(job.state) ? { killed: true } : {}) }, why: `its job ${worker.jobId} is parked — ${how}` };
|
|
2893
3121
|
}
|
|
3122
|
+
/** The job id `claude --bg` prints: `backgrounded · <id> · <name>` for a start under a name, and `backgrounded · <id>` alone for a resume, which passes none. */
|
|
3123
|
+
const BACKGROUNDED = /^backgrounded · (\S+)/m;
|
|
3124
|
+
/** What `claude --bg --resume` adds when the session it was handed still runs, having started a second process on that session: `note: session <id> is already running in the background, so this started a copy as <copy>.` */
|
|
3125
|
+
const STARTED_A_COPY = /session (\S+) is already running in the background, so this started a copy as ([^\s.]+)/;
|
|
2894
3126
|
/** 🔴 #4123 — wakes a parked `claude --bg` session in place with `message`: passed no flags, Claude Code continues the same job with its own saved options. */
|
|
2895
3127
|
export function wakeStoryWorker(sessionId, message, board, cli, now) {
|
|
2896
3128
|
return new Promise((resolve, reject) => {
|
|
2897
3129
|
execFile(cli.cmd, [...cli.args, "--bg", "--resume", sessionId, message], { cwd: board, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
|
|
2898
3130
|
const said = `${stdout}${stderr}`;
|
|
2899
|
-
const
|
|
3131
|
+
const copy = STARTED_A_COPY.exec(said);
|
|
3132
|
+
if (copy !== null) {
|
|
3133
|
+
const started = `claude --bg --resume found session ${copy[1]} still running, so it started a copy as ${copy[2]}, which took the message`;
|
|
3134
|
+
stopStoryWorker(copy[2], cli).then(() => reject(new SessionStillRunning(`${started} and was stopped — the session's own process never received the message`)), (err) => reject(new SessionStillRunning(`${started}, and stopping that copy failed (${err.message}) — the copy still runs with the message beside the session's own process`)));
|
|
3135
|
+
return;
|
|
3136
|
+
}
|
|
3137
|
+
const job = BACKGROUNDED.exec(said);
|
|
2900
3138
|
if (job !== null)
|
|
2901
3139
|
return resolve({ provider: "claude", startedAt: now, jobId: job[1] });
|
|
2902
3140
|
reject(new WorkerNotStarted(`claude --bg --resume ${err === null ? "printed no job id" : `failed (${err.message.split("\n")[0]})`} — ${said.replace(/\s+/g, " ").trim().slice(-300) || "it printed nothing"}`, err !== null && err.killed !== true));
|
|
@@ -2989,9 +3227,12 @@ export async function retireStoryWorker(worker, cli, record, home = claudeHome()
|
|
|
2989
3227
|
* still holds at its prompt is stopped, one still mid-turn is let finish, and either refuses this pass naming it, so the
|
|
2990
3228
|
* story is archived once every process of it has gone; answers what of the worker's own conversation moved.
|
|
2991
3229
|
*/
|
|
2992
|
-
export async function retireStory(
|
|
3230
|
+
export async function retireStory(entry, board, worker, cli, record, home = claudeHome()) {
|
|
3231
|
+
const storyId = entry.storyId;
|
|
2993
3232
|
const held = [];
|
|
2994
|
-
|
|
3233
|
+
const earlier = new Set([...claudeJobsOfStory(storyId, board, 0, home), ...claudeJobsBriefed(entry.brief, home)]);
|
|
3234
|
+
earlier.delete(worker.jobId);
|
|
3235
|
+
for (const jobId of earlier) {
|
|
2995
3236
|
const job = jobRecordOf(jobId, home);
|
|
2996
3237
|
if (job !== "torn" && job !== "gone" && liveClaudeSessions(home).has(job.sessionId)) {
|
|
2997
3238
|
const atPrompt = TURN_OVER.has(job.state);
|
|
@@ -3098,10 +3339,14 @@ export function purgeStoryWorker(sessions, home = claudeHome(), temp = tmpdir())
|
|
|
3098
3339
|
const LAUNCH_TIMEOUT_MS = 60_000;
|
|
3099
3340
|
/** A story's worker, started windowless in the board's folder as a `claude --bg` session whose lifetime is the story's; `cli` is Claude Code's program as this machine runs it. */
|
|
3100
3341
|
export function launchStoryWorker(entry, board, cli, now) {
|
|
3342
|
+
return launchClaudeJob(entry.name, entry.model, workerBrief(entry), board, cli, now);
|
|
3343
|
+
}
|
|
3344
|
+
/** 🔴 #4154 — one windowless `claude --bg` job started in `cwd` under `name` with `brief` as its opening prompt: a story's worker, or FleetView's investigator of a lane. */
|
|
3345
|
+
export function launchClaudeJob(name, model, brief, cwd, cli, now) {
|
|
3101
3346
|
return new Promise((resolve, reject) => {
|
|
3102
|
-
execFile(cli.cmd, [...cli.args, "--bg", "--name",
|
|
3347
|
+
execFile(cli.cmd, [...cli.args, "--bg", "--name", name, "--model", model, "--permission-mode", "bypassPermissions", brief], { cwd, windowsHide: true, timeout: LAUNCH_TIMEOUT_MS }, (err, stdout, stderr) => {
|
|
3103
3348
|
const said = `${stdout}${stderr}`;
|
|
3104
|
-
const job =
|
|
3349
|
+
const job = BACKGROUNDED.exec(said);
|
|
3105
3350
|
if (job !== null)
|
|
3106
3351
|
return resolve({ provider: "claude", startedAt: now, jobId: job[1] });
|
|
3107
3352
|
reject(new WorkerNotStarted(`claude --bg ${err === null ? "printed no job id" : `failed (${err.message.split("\n")[0]})`} — ${said.replace(/\s+/g, " ").trim().slice(-300) || "it printed nothing"}`));
|
|
@@ -439,6 +439,115 @@ function subscriptionFirst({ chain, kinds = {}, kind, keyFallback }) {
|
|
|
439
439
|
const rung = keyFallback ? keyRungOf({ chain, kinds, kind }) : undefined;
|
|
440
440
|
return [...new Set([...chain.filter(paid), ...chain.filter((tier) => !paid(tier)), ...(rung === undefined ? [] : [rung])])];
|
|
441
441
|
}
|
|
442
|
+
/** Where DeepAgent's server answers on this machine. */
|
|
443
|
+
const DEEPAGENT_DOOR = "http://127.0.0.1:7473";
|
|
444
|
+
/** Its MCP door — every dispatcher asks it for each provider's token room (`provider_room`). */
|
|
445
|
+
const DEEPAGENT_MCP_URL = `${DEEPAGENT_DOOR}/mcp`;
|
|
446
|
+
// GATE: how long one `provider_room` read may take before it is a failed reading — twenty seconds, the span ChatGPT's own answer needs for every Codex subscription; past it the room is "could not be read" and the caller keeps its own landing.
|
|
447
|
+
const ROOM_READ_TIMEOUT_MS = 20_000;
|
|
448
|
+
/** The agent CLIs whose subscriptions `provider_room` reads; OpenCode runs on keys and is never among them. */
|
|
449
|
+
const ROOM_PROVIDERS = Object.freeze(["claude", "codex", "copilot"]);
|
|
450
|
+
/** `provider_room` answered anything but a reading: the door gave no answer, a non-200, or a body that is no reading. */
|
|
451
|
+
class RoomReadError extends Error {
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* @typedef {{ state: "room" } | { state: "out", resetsAtMs: number | undefined } | { state: "unread", reason: string }} RoomReading
|
|
455
|
+
* @typedef {Partial<Record<string, RoomReading>>} ProviderRooms
|
|
456
|
+
*/
|
|
457
|
+
/** @param {string} provider */
|
|
458
|
+
function runsOnKeys(provider) {
|
|
459
|
+
return provider === "opencode";
|
|
460
|
+
}
|
|
461
|
+
/** @param {string} provider @param {ProviderRooms} rooms */
|
|
462
|
+
function billsAKey(provider, rooms) {
|
|
463
|
+
return runsOnKeys(provider) || rooms[provider]?.state === "out";
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* One provider's token room out of its `provider_room` entry: some left, spent until a refill, or a reading that could not be taken (never read as spent).
|
|
467
|
+
* @param {any} provider @param {number} now @returns {RoomReading}
|
|
468
|
+
*/
|
|
469
|
+
function roomReadingOf(provider, now) {
|
|
470
|
+
// NULL-OK: field provider is OPTIONAL and therefore it is ok to check for NULL
|
|
471
|
+
if (provider === undefined || provider.state !== "read" || !Array.isArray(provider.accounts)) {
|
|
472
|
+
return { state: "unread", reason: typeof provider?.reason === "string" ? provider.reason : "the provider was not read" };
|
|
473
|
+
}
|
|
474
|
+
const accounts = provider.accounts;
|
|
475
|
+
if (accounts.some((a) => a.state === "read" && a.refused !== true && (a.unlimited === true || (typeof a.roomPct === "number" && a.roomPct > 0))))
|
|
476
|
+
return { state: "room" };
|
|
477
|
+
if (accounts.length === 0 || !accounts.every((a) => a.state === "read" && typeof a.roomPct === "number"))
|
|
478
|
+
return { state: "unread", reason: "an account's room could not be read" };
|
|
479
|
+
if (accounts.some((a) => a.refused !== true && typeof a.resetsAt === "number" && a.resetsAt <= now))
|
|
480
|
+
return { state: "unread", reason: "the reading predates an account's refill" };
|
|
481
|
+
const refills = accounts.filter((a) => a.refused !== true).map((a) => a.resetsAt).filter((r) => typeof r === "number");
|
|
482
|
+
return { state: "out", resetsAtMs: refills.length === 0 ? undefined : Math.min(...refills) };
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The room of each provider a dispatcher can land on, out of `provider_room`'s own answer. A provider the answer does not carry is unread, never out.
|
|
486
|
+
* @param {{ providers?: Record<string, any> }} answer @param {number} now @returns {ProviderRooms}
|
|
487
|
+
*/
|
|
488
|
+
function roomsOf(answer, now) {
|
|
489
|
+
return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, roomReadingOf(answer.providers?.[id], now)]));
|
|
490
|
+
}
|
|
491
|
+
/** Every provider unread, with the reason the whole reading failed. @param {string} reason @returns {ProviderRooms} */
|
|
492
|
+
function unreadRooms(reason) {
|
|
493
|
+
return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, { state: "unread", reason }]));
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* THE one pick of an agent CLI when the caller named none: of `order` the ones `startable` can run, a provider with room
|
|
497
|
+
* first, and `subscriptionFirst` ranking a subscription with room before anything that bills a key.
|
|
498
|
+
* @param {readonly string[]} order @param {ProviderRooms} rooms @param {readonly string[]} startable @returns {string}
|
|
499
|
+
*/
|
|
500
|
+
function autoProvider(order, rooms, startable) {
|
|
501
|
+
const candidates = order.filter((p) => startable.includes(p));
|
|
502
|
+
const tierOf = (p) => (billsAKey(p, rooms) ? p + "-byok" : p + "-cli");
|
|
503
|
+
const rank = (p) => (rooms[p]?.state === "room" ? 0 : 1);
|
|
504
|
+
const chain = [...candidates].sort((x, y) => rank(x) - rank(y)).map(tierOf);
|
|
505
|
+
const first = subscriptionFirst({ chain, keyFallback: false })[0];
|
|
506
|
+
return candidates.find((p) => tierOf(p) === first);
|
|
507
|
+
}
|
|
508
|
+
/** @param {string} url @param {string} project @returns {Promise<{ status: number, body: string }>} */
|
|
509
|
+
async function roomDoorAnswer(url, project) {
|
|
510
|
+
try {
|
|
511
|
+
const res = await fetch(url, {
|
|
512
|
+
method: "POST",
|
|
513
|
+
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "x-deepagent-project": project },
|
|
514
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "provider_room", arguments: {} } }),
|
|
515
|
+
signal: AbortSignal.timeout(ROOM_READ_TIMEOUT_MS),
|
|
516
|
+
});
|
|
517
|
+
return { status: res.status, body: await res.text() };
|
|
518
|
+
}
|
|
519
|
+
catch (err) {
|
|
520
|
+
if (!(err instanceof TypeError) && !(err instanceof Error && err.name === "TimeoutError"))
|
|
521
|
+
throw err;
|
|
522
|
+
const cause = err.cause instanceof Error ? ` (${err.cause.message})` : "";
|
|
523
|
+
throw new RoomReadError(`DeepAgent's door at ${url} gave no answer: ${err.message}${cause}`);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
/** @param {string} text @param {string} what */
|
|
527
|
+
function roomParsedOf(text, what) {
|
|
528
|
+
try {
|
|
529
|
+
return JSON.parse(text);
|
|
530
|
+
}
|
|
531
|
+
catch (err) {
|
|
532
|
+
if (!(err instanceof SyntaxError))
|
|
533
|
+
throw err;
|
|
534
|
+
throw new RoomReadError(`provider_room's ${what} is not JSON (${err.message}): ${text.slice(0, 200)}`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Asks DeepAgent's `provider_room` over its MCP door, for the folder `project` names. Throws RoomReadError when the door answers anything but a reading.
|
|
539
|
+
* @param {string} project @param {string} [url] @param {() => number} [now] @returns {Promise<ProviderRooms>}
|
|
540
|
+
*/
|
|
541
|
+
async function readProviderRooms(project, url = DEEPAGENT_MCP_URL, now = Date.now) {
|
|
542
|
+
const { status, body } = await roomDoorAnswer(url, project);
|
|
543
|
+
if (status !== 200)
|
|
544
|
+
throw new RoomReadError(`provider_room answered HTTP ${status}: ${body.slice(0, 200)}`);
|
|
545
|
+
const reply = roomParsedOf(body, "reply");
|
|
546
|
+
const text = reply.result?.content?.[0]?.text;
|
|
547
|
+
if (reply.result === undefined || reply.result.isError === true || text === undefined)
|
|
548
|
+
throw new RoomReadError(`provider_room gave no reading: ${(text ?? reply.error?.message ?? body).slice(0, 200)}`);
|
|
549
|
+
return roomsOf(roomParsedOf(text, "reading"), now());
|
|
550
|
+
}
|
|
442
551
|
/**
|
|
443
552
|
* Whether the live work has an account with room to run on, worked out from the readings alone and never from a
|
|
444
553
|
* decision's words: covered when the live account read room, uncovered when it read spent (or nobody is logged in and
|
|
@@ -1182,7 +1291,7 @@ function sameHome(home) {
|
|
|
1182
1291
|
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
1183
1292
|
}
|
|
1184
1293
|
/** DeepAgent's resident server, the one process that decides this box's accounts while it answers (#3654). */
|
|
1185
|
-
const DECIDER_DOOR = process.env.BULLSEYE_DECIDER_DOOR ||
|
|
1294
|
+
const DECIDER_DOOR = process.env.BULLSEYE_DECIDER_DOOR || DEEPAGENT_DOOR;
|
|
1186
1295
|
// GATE: how long a mover waits for DeepAgent's server to answer before it reads the server as not deciding and the pad decides
|
|
1187
1296
|
const DECIDER_ASK_MS = 5000;
|
|
1188
1297
|
/**
|
|
@@ -1739,6 +1848,12 @@ module.exports = {
|
|
|
1739
1848
|
writeByokKey,
|
|
1740
1849
|
decide,
|
|
1741
1850
|
subscriptionFirst,
|
|
1851
|
+
RoomReadError,
|
|
1852
|
+
runsOnKeys,
|
|
1853
|
+
billsAKey,
|
|
1854
|
+
unreadRooms,
|
|
1855
|
+
autoProvider,
|
|
1856
|
+
readProviderRooms,
|
|
1742
1857
|
coverageOf,
|
|
1743
1858
|
transientRetried,
|
|
1744
1859
|
firstRefillAt,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omni-notify-mcp",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.378",
|
|
4
4
|
"description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
|
|
5
5
|
"main": "dist/daemon.js",
|
|
6
6
|
"type": "module",
|