omni-notify-mcp 1.3.451 → 1.3.453
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/gateway/mcpDoor.js +6 -6
- package/dist/gateway/terminalDoor.js +4 -8
- package/dist/gateway/terminalPage.js +25 -31
- package/dist/gatewayInstall.cjs +59 -59
- package/dist/shared/agentSession.js +8 -5
- package/dist/shared/conversation/claudeProvider.js +7 -0
- package/dist/shared/conversation/codexProvider.js +36 -1
- package/dist/shared/conversation/conversations.js +9 -7
- package/dist/shared/conversation/copilotProvider.js +29 -2
- package/dist/shared/webhost/autoSwitch.cjs +23 -7
- package/package.json +1 -1
- package/scripts/shared/ownerGuard.cs +0 -665
- package/scripts/shared/ownerGuard.ps1 +0 -31
package/dist/gateway/mcpDoor.js
CHANGED
|
@@ -92,7 +92,7 @@ function projectField(offer) {
|
|
|
92
92
|
}
|
|
93
93
|
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.
|
|
94
94
|
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.
|
|
95
|
-
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
|
|
95
|
+
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 one of ${PROVIDER_NAMES.join(", ")}, or auto (the default). Auto uses DeepAgent's readings to choose a subscription with room before a permitted funded key. A call that goes on with a conversation that already exists needs neither, because both were bound when it was created.
|
|
96
96
|
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.
|
|
97
97
|
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.
|
|
98
98
|
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. No Story is executed twice: FleetView's queue starts a Story's agent only when the live process list shows none working it, and a message that only names a Story — a question about it, a status check — starts nothing. 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.
|
|
@@ -216,7 +216,7 @@ function buildServer(caller, base, offer) {
|
|
|
216
216
|
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"),
|
|
217
217
|
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"),
|
|
218
218
|
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`),
|
|
219
|
-
provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}.
|
|
219
|
+
provider: z.string().min(1).optional().describe(`The agent CLI a NEW conversation runs: exactly one of ${PROVIDER_NAMES.join(", ")}. Use auto or omit it for the shared subscription-first choice. A permitted funded key is considered once eligible subscriptions are exhausted`),
|
|
220
220
|
model: z.string().min(1).optional(),
|
|
221
221
|
}, ({ text, conversation, new: fresh, project, provider, model }) => act(async () => {
|
|
222
222
|
const call = randomUUID().slice(0, 8);
|
|
@@ -260,13 +260,13 @@ function buildServer(caller, base, offer) {
|
|
|
260
260
|
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` };
|
|
261
261
|
}));
|
|
262
262
|
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())));
|
|
263
|
-
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(", ")}.
|
|
263
|
+
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(", ")}. Use auto or omit it for the shared subscription-first choice. A permitted funded key is considered once eligible subscriptions are exhausted`), model: z.string().min(1).optional() }, ({ project, text, provider, model }) => act(async () => {
|
|
264
264
|
const arrived = performance.now();
|
|
265
265
|
const arrival = arrivalOf(requestIdOf(), randomUUID().slice(0, 8));
|
|
266
266
|
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;
|
|
267
267
|
return { id: meta.id, state: meta.state };
|
|
268
268
|
}));
|
|
269
|
-
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(", ")}.
|
|
269
|
+
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(", ")}. Use auto or omit it for the shared subscription-first choice. A permitted funded key is considered once eligible subscriptions are exhausted`), model: z.string().min(1).optional() }, ({ project, provider, model }) => act(async () => {
|
|
270
270
|
const meta = (await createdOn(project, provider, () => caller, (on) => openConversation({ platform: "mcp", technical: true, chat: caller, ...on, model }))).made;
|
|
271
271
|
return { id: meta.id, state: meta.state };
|
|
272
272
|
}));
|
|
@@ -332,10 +332,10 @@ function buildServer(caller, base, offer) {
|
|
|
332
332
|
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))));
|
|
333
333
|
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))));
|
|
334
334
|
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()))));
|
|
335
|
-
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
|
|
335
|
+
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 auto for the shared subscription-first choice), with no turn and nothing spent.`, {
|
|
336
336
|
conversation: z.string().min(1).optional().describe("An existing conversation id whose own CLI to open"),
|
|
337
337
|
project: projectField(offer).optional(),
|
|
338
|
-
provider: z.string().min(1).optional(),
|
|
338
|
+
provider: z.string().min(1).optional().describe("CLI provider, or auto for the shared subscription-first choice"),
|
|
339
339
|
model: z.string().min(1).optional(),
|
|
340
340
|
cols: z.number().int().min(1).max(1000).default(100),
|
|
341
341
|
rows: z.number().int().min(1).max(500).default(30),
|
|
@@ -8,7 +8,7 @@ export { dimensions, validFiles } from "../shared/conversation/terminalTransport
|
|
|
8
8
|
import { GatewayError, closeNativeTerminal, consoleSession, conversationInScope, createdOn, creatorOf, deleteConversation, nativeTerminal, nativeTerminals, openConversation, PROVIDER_NAMES, providerFor, requireOwnCli, requireConversationEnabled, scopedConversation, terminalArriving, viewerOfHeaders } from "./conversationOwner.js";
|
|
9
9
|
import { AgentGateway } from "../agentGateway.js";
|
|
10
10
|
import { bearer, bearerAdmitted, fromThisMachine, personId, sessionExpiresAt } from "./passkeyDoor.js";
|
|
11
|
-
//
|
|
11
|
+
// Keep idle tunnels alive; the shared browser runtime confirms silence only while this daemon answers.
|
|
12
12
|
const TERMINAL_PING_MS = 25_000;
|
|
13
13
|
export function terminalSockets(server, token) {
|
|
14
14
|
const sockets = new WebSocketServer({ noServer: true, handleProtocols: () => "bn-terminal" });
|
|
@@ -37,13 +37,9 @@ export function terminalSockets(server, token) {
|
|
|
37
37
|
const given = bearer(req);
|
|
38
38
|
const terminal = nativeTerminal(personId(), match[1]);
|
|
39
39
|
sockets.handleUpgrade(req, socket, head, (ws) => {
|
|
40
|
-
//
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const keepalive = setInterval(() => { if (!answered) {
|
|
44
|
-
ws.terminate();
|
|
45
|
-
return;
|
|
46
|
-
} answered = false; ws.ping(); }, TERMINAL_PING_MS);
|
|
40
|
+
// Do not terminate on a timer: after a busy event loop, a pong may still be queued for delivery.
|
|
41
|
+
const keepalive = setInterval(() => { if (ws.readyState === ws.OPEN)
|
|
42
|
+
ws.ping(); }, TERMINAL_PING_MS);
|
|
47
43
|
ws.on("close", () => clearInterval(keepalive));
|
|
48
44
|
attachTerminalSocket(ws, terminal, {
|
|
49
45
|
admitted: () => bearerAdmitted(req, token),
|
|
@@ -136,9 +136,9 @@ function sizePhone(){
|
|
|
136
136
|
document.body.classList.toggle("phone",phone);document.documentElement.style.setProperty("--k",String(phoneScale));
|
|
137
137
|
if(terminal&&Math.round(15*was)!==Math.round(15*phoneScale))refit();
|
|
138
138
|
}
|
|
139
|
-
var view=0,sent={},listResize=null,terminal,fitAddon,
|
|
139
|
+
var view=0,sent={},listResize=null,terminal,fitAddon,kept=null,observer,arrival=null,socketDown=false,reopened=null,sender=Math.random().toString(36).slice(2)+Date.now().toString(36);
|
|
140
140
|
var REOPENED="A new CLI of this conversation — the one before is gone, and its screen was not kept.";
|
|
141
|
-
|
|
141
|
+
function socketNow(){return kept===null?null:kept.socket();}
|
|
142
142
|
sizePhone();window.addEventListener("resize",sizePhone);
|
|
143
143
|
if(window.visualViewport){var fitKeyboard=function(){document.body.style.height=phone?visualViewport.height+"px":"";};visualViewport.addEventListener("resize",fitKeyboard);fitKeyboard();}
|
|
144
144
|
var AGENTS = ${JSON.stringify(PROVIDER_CHOICES)};
|
|
@@ -162,7 +162,7 @@ function tool(id,icon,label,cls,brief){var b=el("button",cls,icon);b.id=id;b.app
|
|
|
162
162
|
|
|
163
163
|
function show(name,heading){
|
|
164
164
|
view++;
|
|
165
|
-
|
|
165
|
+
if(kept!==null){kept.stop();kept=null;}if(observer){observer.disconnect();observer=null;}if(terminal){terminal.dispose();terminal=null;}
|
|
166
166
|
if(name!=="terminal"){socketDown=false;if(!gatewayDown)window.bullseyeConnection.live();document.getElementById("keybar").hidden=true;main.style.display="";main.style.flexDirection="";tools.replaceChildren();}
|
|
167
167
|
title.textContent=heading;
|
|
168
168
|
var inList=name==="list";
|
|
@@ -182,11 +182,11 @@ function show(name,heading){
|
|
|
182
182
|
return view;
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
-
function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}function down(what,method,path){if(method==="GET"&&path==="/v1/conversations")window.bullseyeConnection.reconnecting(what,8000);else if(method==="GET"&&path==="/v1/panel")window.bullseyeConnection.reconnecting(what,5000);else if(method==="GET"&&path.indexOf("/v1/terminals/")===0)window.bullseyeConnection.reconnecting(what,1000);}
|
|
185
|
+
function scoped(h){if(scope!==null)h["x-bullseye-project"]=scope;return h}function down(what,method,path){var socket=socketNow();if(socket!==null&&socket.readyState===WebSocket.OPEN)return;if(method==="GET"&&path==="/v1/conversations")window.bullseyeConnection.reconnecting(what,8000);else if(method==="GET"&&path==="/v1/panel")window.bullseyeConnection.reconnecting(what,5000);else if(method==="GET"&&path.indexOf("/v1/terminals/")===0)window.bullseyeConnection.reconnecting(what,1000);}
|
|
186
186
|
async function reach(method,path,body,signal){var response;try{response=await fetch(path,{method:method,headers:scoped({authorization:"Bearer "+token,"content-type":"application/json"}),body:body===undefined?undefined:JSON.stringify(body),signal:signal});}catch(e){if(e.name!=="AbortError")down("the connection to the Notify service",method,path);throw e;}if(response.status>=502)down("the connection to the Notify service (HTTP "+response.status+")",method,path);else if(!socketDown)window.bullseyeConnection.live();return response;}
|
|
187
187
|
async function api(method,path,body,signal){var response=await reach(method,path,body,signal);var data=await told(response);if(!response.ok){if(response.status===401)signIn("Sign in again to reach your CLI.");var error=Error(data.error||"Request failed");error.status=response.status;throw error;}return data;}
|
|
188
188
|
function fail(error){liveNotice(plainWhy(error),"error");}
|
|
189
|
-
function ordered(id,act,body){if(!socket||socket.readyState!==WebSocket.OPEN)return;socket.send(JSON.stringify(Object.assign({kind:act},body)));}
|
|
189
|
+
function ordered(id,act,body){var socket=socketNow();if(!socket||socket.readyState!==WebSocket.OPEN)return;socket.send(JSON.stringify(Object.assign({kind:act},body)));}
|
|
190
190
|
/** The last folder of a path, so a row names its project without printing the whole path. */
|
|
191
191
|
function base(folder){var parts=String(folder).split(/[/\\\\]+/).filter(function(p){return p;});return parts[parts.length-1]||String(folder);}
|
|
192
192
|
/** Where a conversation came from: an MCP client, or the person in this page (Telegram, REST and the rest count as User). */
|
|
@@ -269,15 +269,15 @@ async function newAgentView(){
|
|
|
269
269
|
var mine=show("new","New Agent");
|
|
270
270
|
var setup=el("div","setup"),provider=el("select"),project=el("select"),model=el("input"),open=el("button","go","▶ New Agent");
|
|
271
271
|
provider.setAttribute("aria-label","CLI provider");project.setAttribute("aria-label","Project");model.setAttribute("aria-label","Model");model.placeholder="Model (CLI default if empty)";model.autocapitalize="none";model.spellcheck=false;model.enterKeyHint="go";
|
|
272
|
-
//
|
|
273
|
-
var cliPlaceholder=el("option","","
|
|
274
|
-
cliPlaceholder.value="";folderPlaceholder.value="";provider.append(cliPlaceholder);project.append(folderPlaceholder);
|
|
272
|
+
// Auto is the default provider. With no workspace named, the CLI starts at the workspace root and routes its work into the projects.
|
|
273
|
+
var cliPlaceholder=el("option","","Auto (subscription first)"),folderPlaceholder=el("option","","Workspace root (any project)");
|
|
274
|
+
cliPlaceholder.value="auto";folderPlaceholder.value="";provider.append(cliPlaceholder);project.append(folderPlaceholder);
|
|
275
275
|
var problem=el("div","err");problem.hidden=true;problem.setAttribute("role","alert");
|
|
276
276
|
var explain=el("p","system");
|
|
277
277
|
setup.append(provider,project,model,open);main.append(setup,explain,problem);
|
|
278
278
|
var folders=[],catalog=[],unread=null;
|
|
279
279
|
function refuse(text){problem.textContent="❌ "+text;problem.hidden=false;}
|
|
280
|
-
function cliName(){var chosen=catalog.filter(function(entry){return entry.name===provider.value;})[0];return chosen?(chosen.label||chosen.name):"the
|
|
280
|
+
function cliName(){var chosen=catalog.filter(function(entry){return entry.name===provider.value;})[0];return chosen?(chosen.label||chosen.name):"the provider Auto picks";}
|
|
281
281
|
function sync(){
|
|
282
282
|
var chosen=catalog.filter(function(entry){return entry.name===provider.value;})[0];
|
|
283
283
|
model.hidden=!(chosen&&chosen.model);if(model.hidden)model.value="";
|
|
@@ -298,7 +298,7 @@ async function newAgentView(){
|
|
|
298
298
|
open.onclick=async function(){
|
|
299
299
|
if(unread!==null){swap("new");return;}
|
|
300
300
|
open.disabled=true;problem.hidden=true;liveNotice("⏳ Starting "+cliName()+"…");
|
|
301
|
-
try{var s=await api("POST","/v1/terminals",{provider:provider.value
|
|
301
|
+
try{var s=await api("POST","/v1/terminals",{provider:provider.value,project:project.value||undefined,model:model.hidden?"":model.value,cols:100,rows:30});if(mine===view)swap("term",s.id);}
|
|
302
302
|
catch(error){if(mine!==view)return;refuse("Not started: "+plainWhy(error));liveNotice("Not started — the reason is below.","error");open.disabled=false;}
|
|
303
303
|
};
|
|
304
304
|
}
|
|
@@ -454,7 +454,7 @@ async function cliAttach(id,origin){
|
|
|
454
454
|
};
|
|
455
455
|
var uploads=Promise.resolve(),sentPaths=[];
|
|
456
456
|
function upload(files){
|
|
457
|
-
var destination=
|
|
457
|
+
var destination=socketNow();
|
|
458
458
|
if(!destination||destination.readyState!==WebSocket.OPEN){liveNotice("File transfer failed: reconnect to the CLI first.","error");return;}
|
|
459
459
|
liveNotice("⏳ Writing "+files.length+(files.length===1?" file":" files")+" on the CLI machine…");
|
|
460
460
|
uploads=uploads.then(async function(){
|
|
@@ -463,7 +463,7 @@ async function cliAttach(id,origin){
|
|
|
463
463
|
var data=await new Promise(function(resolve,reject){var reader=new FileReader();reader.onload=function(){resolve(String(reader.result).split(",")[1]);};reader.onerror=function(){reject(Error("Could not read "+file.name));};reader.onabort=function(){reject(Error("Reading "+file.name+" was cancelled."));};reader.readAsDataURL(file);});
|
|
464
464
|
contents.push({name:file.name||"clipboard.png",data:data});
|
|
465
465
|
}
|
|
466
|
-
if(mine!==view||
|
|
466
|
+
if(mine!==view||socketNow()!==destination||destination.readyState!==WebSocket.OPEN)throw Error("The terminal disconnected before the files were sent; paste or drop them again.");
|
|
467
467
|
destination.send(JSON.stringify({kind:"files",files:contents}));
|
|
468
468
|
}).catch(function(error){if(mine===view)liveNotice("File transfer failed: "+error.message,"error");});
|
|
469
469
|
}
|
|
@@ -530,7 +530,7 @@ async function cliAttach(id,origin){
|
|
|
530
530
|
},true);
|
|
531
531
|
var keybar=document.getElementById("keybar"),ctrlHeld=false,ctrlKey=null;
|
|
532
532
|
function disarm(){ctrlHeld=false;ctrlKey.classList.remove("armed");}
|
|
533
|
-
var unacked=[],inputs=0,wheeling=false,from=sender+"."+mine;function typed(body,mark,auto){if(term.options.disableStdin){liveNotice("Not sent — this CLI is no longer connected. Press 🔌 Reattach.","error");return;}if(!owner&&!auto){claim();mark=withhold;}inputs+=1;var sent={id:inputs,frame:JSON.stringify(Object.assign({kind:"input",from:from,id:inputs},body))};unacked.push(sent);if(socket!==null&&socket.readyState===WebSocket.OPEN)socket.send(sent.frame);mark(sent.id);}
|
|
533
|
+
var unacked=[],inputs=0,wheeling=false,from=sender+"."+mine;function typed(body,mark,auto){if(term.options.disableStdin){liveNotice("Not sent — this CLI is no longer connected. Press 🔌 Reattach.","error");return;}if(!owner&&!auto){claim();mark=withhold;}inputs+=1;var sent={id:inputs,frame:JSON.stringify(Object.assign({kind:"input",from:from,id:inputs},body))};unacked.push(sent);var socket=socketNow();if(socket!==null&&socket.readyState===WebSocket.OPEN)socket.send(sent.frame);mark(sent.id);}
|
|
534
534
|
function sendKey(data){if(ctrlHeld){disarm();data=ctrlBarSeq(data);}typed({data:data},withhold);}
|
|
535
535
|
keybar.replaceChildren();keybar.hidden=false;
|
|
536
536
|
[NEW_LINE].concat(KEY_BAR.slice(0,7),[{id:"ctrl",label:"Ctrl",title:"Ctrl (sticky)"}],KEY_BAR.slice(7)).forEach(function(key){
|
|
@@ -553,7 +553,7 @@ async function cliAttach(id,origin){
|
|
|
553
553
|
}
|
|
554
554
|
}
|
|
555
555
|
function claim(){if(owner)return;owner=true;refit();}
|
|
556
|
-
refit=function(){if(mine!==view)return;fitShown();if(!owner||!socket||socket.readyState!==WebSocket.OPEN||host.clientWidth===0||host.clientHeight===0)return;fitAddon.fit();claimed={cols:term.cols,rows:term.rows};held=shown;ordered(id,"resize",claimed);};
|
|
556
|
+
refit=function(){var socket=socketNow();if(mine!==view)return;fitShown();if(!owner||!socket||socket.readyState!==WebSocket.OPEN||host.clientWidth===0||host.clientHeight===0)return;fitAddon.fit();claimed={cols:term.cols,rows:term.rows};held=shown;ordered(id,"resize",claimed);};
|
|
557
557
|
function sized(frame){
|
|
558
558
|
shown={cols:frame.cols,rows:frame.rows};
|
|
559
559
|
if(owner&&claimed){if(frame.cols===claimed.cols&&frame.rows===claimed.rows)held=claimed;else if(!held)held=shown;else if(frame.cols!==held.cols||frame.rows!==held.rows){owner=false;claimed=held=null;}}
|
|
@@ -566,25 +566,12 @@ async function cliAttach(id,origin){
|
|
|
566
566
|
reopened=null;
|
|
567
567
|
close.onclick=async function(){close.disabled=true;try{await api("DELETE","/v1/terminals/"+id);swap("list");}catch(error){close.disabled=false;fail(error);}};
|
|
568
568
|
observer.observe(host);
|
|
569
|
-
var WHAT="the terminal connection to the CLI"
|
|
570
|
-
function again(wait){socketDown=true;reattached=true;window.bullseyeConnection.reconnecting(WHAT,wait);liveFailed("reattaching to the same CLI…");reconnect=setTimeout(findCli,wait);}
|
|
571
|
-
function abandon(ws,wait){ws.onopen=ws.onmessage=ws.onclose=ws.onerror=null;ws.close();if(socket===ws)socket=null;again(wait);}
|
|
572
|
-
lost=function(ws){if(mine===view&&socket===ws)abandon(ws,window.bullseyeConnection.closed(reattached));};
|
|
573
|
-
function connect(){
|
|
574
|
-
if(mine!==view)return;
|
|
575
|
-
var ws=new WebSocket((location.protocol==="https:"?"wss://":"ws://")+location.host+"/v1/terminals/"+id+"/ws",["bn-terminal","bn-bearer."+token]);socket=ws;
|
|
576
|
-
var frames=Promise.resolve(),opened=false;
|
|
577
|
-
setTimeout(function(){if(mine===view&&socket===ws&&ws.readyState===WebSocket.CONNECTING)abandon(ws,window.bullseyeConnection.failed());},window.bullseyeConnection.limit());
|
|
578
|
-
ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;heard();window.bullseyeConnection.opened(function(){return socket===ws&&ws.readyState===WebSocket.OPEN;},window.bullseyeConnection.live);term.options.disableStdin=false;if(opening||unacked.length){opening=false;owner=false;claim();}else if(owner&&claimed){held=claimed;rejoined=true;fitShown();}else{owner=false;fitShown();}unacked.forEach(function(sent){ws.send(sent.frame);});term.focus();};
|
|
579
|
-
ws.onmessage=function(event){if(socket===ws)heard();var frame=JSON.parse(event.data);if(frame.pong)return;if(frame.ack!==undefined){acked=Math.max(acked,frame.ack);unacked=unacked.filter(function(sent){return sent.id>frame.ack;});return;}var seen=acked;frames=frames.then(async function(){if(mine!==view)return;if(frame.files){if(frame.error)liveNotice(frame.error,"error");else{sentPaths=sentPaths.concat(frame.paths);liveNotice("Sent to CLI: "+frame.paths.map(function(sent){return phone?base(sent):sent;}).join(" · "));}return;}if(frame.error){liveNotice(frame.error,"error");return;}sized(frame);var behind=frame.reset?term.buffer.active.baseY-term.buffer.active.viewportY:0;if(frame.reset){forget();cursorShown=true;term.reset();}var shown=frame.data.match(/\\x1b\\[\\?25[hl]/g);if(shown)cursorShown=shown[shown.length-1].slice(-1)==="h";await new Promise(function(done){term.write(frame.data,done);});if(mine!==view)return;fitShown();reconcile(seen);if(behind>0)term.scrollLines(-behind);cli.provider=frame.provider;cli.project=frame.project;liveRead();if(frame.ended){forget();liveEnded("CLI ended"+(frame.failure?" · "+frame.failure:""));}else if(frame.failure&&frame.failure!==cli.failure)liveNotice(frame.failure,"error");cli.failure=frame.failure;}).catch(fail);};
|
|
580
|
-
ws.onclose=function(event){if(mine!==view)return;forget();var ending=event.code===1000||(event.code===1008&&event.reason==="Sign in again");if(ending){term.options.disableStdin=true;unacked=[];}if(event.code===1000){socketDown=false;window.bullseyeConnection.live();liveEnded("CLI ended");return;}if(event.code===1008&&event.reason==="Sign in again"){socketDown=false;window.bullseyeConnection.live();signIn("Your sign-in expired. Sign in again to return to this CLI.");return;}again(opened?window.bullseyeConnection.closed(reattached):window.bullseyeConnection.failed());};
|
|
581
|
-
ws.onerror=function(){socketDown=true;liveFailed("reattaching to the same CLI…");};
|
|
582
|
-
}
|
|
569
|
+
var WHAT="the terminal connection to the CLI";
|
|
583
570
|
// GATE: a reattach's read of its CLI that has not answered in this long is abandoned and asked again with backoff, so a dead link never leaves the page waiting on it
|
|
584
571
|
var FIND_MS=8000;
|
|
585
572
|
// GATE: opening the CLI again that has not answered in this long is abandoned and asked again with backoff; it covers a CLI's own start
|
|
586
573
|
var START_MS=30000;
|
|
587
|
-
function findCli(){
|
|
574
|
+
function findCli(connect,later){
|
|
588
575
|
if(mine!==view)return;
|
|
589
576
|
api("GET","/v1/terminals/"+id,undefined,AbortSignal.timeout(FIND_MS)).then(connect,function(error){
|
|
590
577
|
if(mine!==view)return;
|
|
@@ -597,8 +584,15 @@ async function cliAttach(id,origin){
|
|
|
597
584
|
});
|
|
598
585
|
});
|
|
599
586
|
}
|
|
600
|
-
|
|
601
|
-
|
|
587
|
+
kept=window.bullseyeConnection.keep({what:WHAT,path:"/passkey/state",
|
|
588
|
+
open:function(){var ws=new WebSocket((location.protocol==="https:"?"wss://":"ws://")+location.host+"/v1/terminals/"+id+"/ws",["bn-terminal","bn-bearer."+token]);ws.frames=Promise.resolve();return ws;},
|
|
589
|
+
attach:findCli,
|
|
590
|
+
opened:function(ws){if(mine!==view)return;socketDown=false;term.options.disableStdin=false;if(opening||unacked.length){opening=false;owner=false;claim();}else if(owner&&claimed){held=claimed;rejoined=true;fitShown();}else{owner=false;fitShown();}unacked.forEach(function(sent){ws.send(sent.frame);});term.focus();},
|
|
591
|
+
message:function(ws,event){var frame=JSON.parse(event.data);if(frame.pong)return;if(frame.ack!==undefined){acked=Math.max(acked,frame.ack);unacked=unacked.filter(function(sent){return sent.id>frame.ack;});return;}var seen=acked;ws.frames=ws.frames.then(async function(){if(mine!==view)return;if(frame.files){if(frame.error)liveNotice(frame.error,"error");else{sentPaths=sentPaths.concat(frame.paths);liveNotice("Sent to CLI: "+frame.paths.map(function(sent){return phone?base(sent):sent;}).join(" · "));}return;}if(frame.error){liveNotice(frame.error,"error");return;}sized(frame);var behind=frame.reset?term.buffer.active.baseY-term.buffer.active.viewportY:0;if(frame.reset){forget();cursorShown=true;term.reset();}var shown=frame.data.match(/\\x1b\\[\\?25[hl]/g);if(shown)cursorShown=shown[shown.length-1].slice(-1)==="h";await new Promise(function(done){term.write(frame.data,done);});if(mine!==view)return;fitShown();reconcile(seen);if(behind>0)term.scrollLines(-behind);cli.provider=frame.provider;cli.project=frame.project;liveRead();if(frame.ended){forget();liveEnded("CLI ended"+(frame.failure?" · "+frame.failure:""));}else if(frame.failure&&frame.failure!==cli.failure)liveNotice(frame.failure,"error");cli.failure=frame.failure;}).catch(fail);},
|
|
592
|
+
down:function(){socketDown=true;liveFailed("reattaching to the same CLI…");},
|
|
593
|
+
closed:function(event){if(mine!==view)return;forget();var ending=event.code===1000||(event.code===1008&&event.reason==="Sign in again");if(ending){term.options.disableStdin=true;unacked=[];}if(event.code===1000){socketDown=false;window.bullseyeConnection.live();liveEnded("CLI ended");return true;}if(event.code===1008&&event.reason==="Sign in again"){socketDown=false;window.bullseyeConnection.live();signIn("Your sign-in expired. Sign in again to return to this CLI.");return true;}return false;},
|
|
594
|
+
ping:function(alive){alive.send('{"kind":"ping"}');}});
|
|
595
|
+
kept.connect();
|
|
602
596
|
}
|
|
603
597
|
${CONVERSATIONS_VIEWS}
|
|
604
598
|
btnBack.onclick=goBack;
|
package/dist/gatewayInstall.cjs
CHANGED
|
@@ -1,59 +1,59 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
const fs = require("fs");
|
|
4
|
-
const path = require("path");
|
|
5
|
-
const { spawn } = require("child_process");
|
|
6
|
-
|
|
7
|
-
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
|
|
8
|
-
|
|
9
|
-
function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
|
|
10
|
-
return [
|
|
11
|
-
deploy,
|
|
12
|
-
"--domain", domain,
|
|
13
|
-
...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
|
|
14
|
-
// NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
|
|
15
|
-
"--project-root", projectRoot ?? home,
|
|
16
|
-
"--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
|
|
17
|
-
"--notify-dir", doorsDir,
|
|
18
|
-
];
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function runDeploy({ node, args, cwd, env, onOutput }) {
|
|
22
|
-
return new Promise((resolve, reject) => {
|
|
23
|
-
const child = spawn(node, args, { windowsHide: true, cwd, env });
|
|
24
|
-
child.stdout.on("data", (chunk) => onOutput(String(chunk)));
|
|
25
|
-
child.stderr.on("data", (chunk) => onOutput(String(chunk)));
|
|
26
|
-
child.on("error", reject);
|
|
27
|
-
child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
|
|
32
|
-
|
|
33
|
-
function writeRecord(file, record) {
|
|
34
|
-
const staged = `${file}.${process.pid}.tmp`;
|
|
35
|
-
fs.writeFileSync(staged, JSON.stringify(record, null, 2));
|
|
36
|
-
try {
|
|
37
|
-
fs.renameSync(staged, file);
|
|
38
|
-
} catch (err) {
|
|
39
|
-
fs.rmSync(staged, { force: true });
|
|
40
|
-
throw err;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async function runRecorded(recordFile, recordText) {
|
|
45
|
-
const record = { ...JSON.parse(recordText), pid: process.pid };
|
|
46
|
-
const log = recordFile.replace(/\.json$/, ".log");
|
|
47
|
-
const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
|
|
48
|
-
try {
|
|
49
|
-
const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
|
|
50
|
-
write({ endedAt: new Date().toISOString(), ...ended });
|
|
51
|
-
} catch (err) {
|
|
52
|
-
// OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
|
|
53
|
-
write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
|
|
58
|
-
|
|
59
|
-
module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { spawn } = require("child_process");
|
|
6
|
+
|
|
7
|
+
const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
|
|
8
|
+
|
|
9
|
+
function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
|
|
10
|
+
return [
|
|
11
|
+
deploy,
|
|
12
|
+
"--domain", domain,
|
|
13
|
+
...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
|
|
14
|
+
// NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
|
|
15
|
+
"--project-root", projectRoot ?? home,
|
|
16
|
+
"--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
|
|
17
|
+
"--notify-dir", doorsDir,
|
|
18
|
+
];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function runDeploy({ node, args, cwd, env, onOutput }) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const child = spawn(node, args, { windowsHide: true, cwd, env });
|
|
24
|
+
child.stdout.on("data", (chunk) => onOutput(String(chunk)));
|
|
25
|
+
child.stderr.on("data", (chunk) => onOutput(String(chunk)));
|
|
26
|
+
child.on("error", reject);
|
|
27
|
+
child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
|
|
32
|
+
|
|
33
|
+
function writeRecord(file, record) {
|
|
34
|
+
const staged = `${file}.${process.pid}.tmp`;
|
|
35
|
+
fs.writeFileSync(staged, JSON.stringify(record, null, 2));
|
|
36
|
+
try {
|
|
37
|
+
fs.renameSync(staged, file);
|
|
38
|
+
} catch (err) {
|
|
39
|
+
fs.rmSync(staged, { force: true });
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function runRecorded(recordFile, recordText) {
|
|
45
|
+
const record = { ...JSON.parse(recordText), pid: process.pid };
|
|
46
|
+
const log = recordFile.replace(/\.json$/, ".log");
|
|
47
|
+
const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
|
|
48
|
+
try {
|
|
49
|
+
const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
|
|
50
|
+
write({ endedAt: new Date().toISOString(), ...ended });
|
|
51
|
+
} catch (err) {
|
|
52
|
+
// OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
|
|
53
|
+
write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
|
|
58
|
+
|
|
59
|
+
module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
|
|
@@ -1861,11 +1861,11 @@ export class TableReader {
|
|
|
1861
1861
|
});
|
|
1862
1862
|
});
|
|
1863
1863
|
}
|
|
1864
|
-
ask(request) {
|
|
1864
|
+
async ask(request) {
|
|
1865
1865
|
if (this.phase === "closed") {
|
|
1866
1866
|
return Promise.reject(new ProcessTableUnreadable("the process table reader was closed with the build that owned it"));
|
|
1867
1867
|
}
|
|
1868
|
-
const child = this.child ?? this.start();
|
|
1868
|
+
const child = this.child ?? await this.start();
|
|
1869
1869
|
return new Promise((resolve, reject) => {
|
|
1870
1870
|
let out = "";
|
|
1871
1871
|
const settle = () => {
|
|
@@ -1909,8 +1909,11 @@ export class TableReader {
|
|
|
1909
1909
|
child.stdin.write(`${request}\n`);
|
|
1910
1910
|
});
|
|
1911
1911
|
}
|
|
1912
|
-
start() {
|
|
1913
|
-
const { file, args, env } = this.launch();
|
|
1912
|
+
async start() {
|
|
1913
|
+
const { file, args, env } = await this.launch();
|
|
1914
|
+
if (this.phase === "closed") {
|
|
1915
|
+
throw new ProcessTableUnreadable("the process table reader was closed while its launch was being resolved");
|
|
1916
|
+
}
|
|
1914
1917
|
const child = spawn(file, [...args], {
|
|
1915
1918
|
cwd: tmpdir(),
|
|
1916
1919
|
env: env ?? process.env,
|
|
@@ -1962,7 +1965,7 @@ export class ProcessTable {
|
|
|
1962
1965
|
msys;
|
|
1963
1966
|
constructor(gitBash) {
|
|
1964
1967
|
this.windows = new TableReader(() => windowsTableLaunch(process.pid));
|
|
1965
|
-
this.msys = new TableReader(() => ({ file: gitBash(), args: ["-c", 'eval "$AGENT_SESSION_MSYS_TABLE"'], env: { ...process.env, AGENT_SESSION_MSYS_TABLE: MSYS_TABLE_SCRIPT } }));
|
|
1968
|
+
this.msys = new TableReader(async () => ({ file: await gitBash(), args: ["-c", 'eval "$AGENT_SESSION_MSYS_TABLE"'], env: { ...process.env, AGENT_SESSION_MSYS_TABLE: MSYS_TABLE_SCRIPT } }));
|
|
1966
1969
|
}
|
|
1967
1970
|
dispose() {
|
|
1968
1971
|
this.windows.close();
|
|
@@ -23,6 +23,12 @@ export function createClaudeDriver(runtime) {
|
|
|
23
23
|
function configDir() {
|
|
24
24
|
return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
25
25
|
}
|
|
26
|
+
/** The same environment and settings sources the native CLI will load. */
|
|
27
|
+
function usesKey(project) {
|
|
28
|
+
const hasKey = (env) => Boolean(env.ANTHROPIC_BASE_URL || env.ANTHROPIC_API_KEY);
|
|
29
|
+
const settings = [join(configDir(), "settings.json"), join(project, ".claude", "settings.json"), join(project, ".claude", "settings.local.json")];
|
|
30
|
+
return hasKey(process.env) || settings.some((file) => existsSync(file) && hasKey(JSON.parse(readFileSync(file, "utf8")).env ?? {}));
|
|
31
|
+
}
|
|
26
32
|
function projectsDir() {
|
|
27
33
|
return join(configDir(), "projects");
|
|
28
34
|
}
|
|
@@ -351,6 +357,7 @@ export function createClaudeDriver(runtime) {
|
|
|
351
357
|
label: "Claude Code",
|
|
352
358
|
command: "claude",
|
|
353
359
|
routesAtRoot: true,
|
|
360
|
+
usesKey,
|
|
354
361
|
nativeArgs: (model) => model ? ["--model", model] : [],
|
|
355
362
|
open: (spec) => new ClaudeCliSession(spec),
|
|
356
363
|
};
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* one folder, so a new session's rollout is told apart by the prompt typed into this CLI. A thread BN archived is moved
|
|
9
9
|
* back out of Codex's archive before its CLI resumes it.
|
|
10
10
|
*/
|
|
11
|
-
import { existsSync, readdirSync, statSync } from "fs";
|
|
11
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "fs";
|
|
12
12
|
import { homedir } from "os";
|
|
13
13
|
import { join } from "path";
|
|
14
14
|
import { archiveCodexThread } from "./codexArchive.js";
|
|
@@ -169,11 +169,44 @@ export function createCodexDriver(runtime) {
|
|
|
169
169
|
rollout.prompts.push(news.text);
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
+
/** Which provider and login the native CLI reads for the next launch. */
|
|
173
|
+
function usesKey() {
|
|
174
|
+
const config = join(codexHome(), "config.toml");
|
|
175
|
+
if (existsSync(config)) {
|
|
176
|
+
const top = readFileSync(config, "utf8").split(/^\s*\[/m, 1)[0];
|
|
177
|
+
const selected = /^\s*model_provider\s*=\s*(["'])([^"']+)\1/m.exec(top);
|
|
178
|
+
if (selected && selected[2] !== "openai")
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
const auth = join(codexHome(), "auth.json");
|
|
182
|
+
if (existsSync(auth)) {
|
|
183
|
+
const login = JSON.parse(readFileSync(auth, "utf8"));
|
|
184
|
+
if (login.auth_mode === "chatgpt")
|
|
185
|
+
return false;
|
|
186
|
+
if (login.auth_mode === "apikey" || login.OPENAI_API_KEY)
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
return Boolean(process.env.OPENAI_API_KEY);
|
|
190
|
+
}
|
|
191
|
+
/** Codex's workspace-root session loads a project's instructions before acting there. */
|
|
192
|
+
function rootArgs(project) {
|
|
193
|
+
if (!runtime.store.isRootFolder(project))
|
|
194
|
+
return [];
|
|
195
|
+
const folders = runtime.store.listedFolders();
|
|
196
|
+
const instructions = [
|
|
197
|
+
"This is the workspace root. Route each request to the project it concerns.",
|
|
198
|
+
"Before working in a project, read and follow its AGENTS.md and every file that loader names, or its CLAUDE.md and claude.app.md when present and there is no AGENTS.md.",
|
|
199
|
+
"Resolve cross-project requests separately under each project's instructions.",
|
|
200
|
+
...folders,
|
|
201
|
+
].join("\n");
|
|
202
|
+
return ["-c", "developer_instructions=" + JSON.stringify(instructions), ...folders.flatMap((folder) => ["--add-dir", folder])];
|
|
203
|
+
}
|
|
172
204
|
const codexCli = {
|
|
173
205
|
get provider() { return codexProvider; },
|
|
174
206
|
args: (spec, resumes) => [
|
|
175
207
|
...(resumes ? ["resume"] : []),
|
|
176
208
|
"--dangerously-bypass-approvals-and-sandbox",
|
|
209
|
+
...rootArgs(spec.project),
|
|
177
210
|
...(spec.model === undefined ? [] : ["-m", spec.model]),
|
|
178
211
|
...(resumes ? [spec.sessionId] : []),
|
|
179
212
|
],
|
|
@@ -184,6 +217,8 @@ export function createCodexDriver(runtime) {
|
|
|
184
217
|
name: "codex",
|
|
185
218
|
label: "Codex",
|
|
186
219
|
command: "codex",
|
|
220
|
+
routesAtRoot: true,
|
|
221
|
+
usesKey,
|
|
187
222
|
nativeArgs: (model) => model ? ["-m", model] : [],
|
|
188
223
|
open: (spec) => new LoggedCliSession(spec, codexCli, runtime),
|
|
189
224
|
archive: (spec, sessionId) => archiveCodexThread(spec, sessionId, "thread/archive"),
|
|
@@ -12,6 +12,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renam
|
|
|
12
12
|
import { randomUUID } from "crypto";
|
|
13
13
|
import { performance } from "perf_hooks";
|
|
14
14
|
import { EventEmitter } from "events";
|
|
15
|
+
import { homedir } from "os";
|
|
15
16
|
import { basename, dirname, join, resolve } from "path";
|
|
16
17
|
import autoSwitch from "../webhost/autoSwitch.cjs";
|
|
17
18
|
import { workspacesFile, workspacesHere } from "../webhost/workspaceList.js";
|
|
@@ -632,7 +633,7 @@ export function createConversationStore(host, registry) {
|
|
|
632
633
|
const named = typeof provider === "string" ? registry().get(provider) : undefined;
|
|
633
634
|
// NULL-OK: field named is OPTIONAL and therefore it is ok to check for NULL
|
|
634
635
|
if (named === undefined)
|
|
635
|
-
throw new GatewayError(400, `provider must be exactly one of ${registry().names.join(", ")}, or
|
|
636
|
+
throw new GatewayError(400, `provider must be exactly one of ${registry().names.join(", ")}, or auto`);
|
|
636
637
|
return named.name;
|
|
637
638
|
}
|
|
638
639
|
// 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.
|
|
@@ -647,7 +648,7 @@ export function createConversationStore(host, registry) {
|
|
|
647
648
|
* workspace root only those that load every project's rules there — weighed by DeepAgent's `provider_room` read for the folder.
|
|
648
649
|
*/
|
|
649
650
|
async function pickedCli(provider, folder) {
|
|
650
|
-
if (provider !== undefined && !(typeof provider === "string" && provider.trim() === "")) {
|
|
651
|
+
if (provider !== undefined && provider !== "auto" && !(typeof provider === "string" && provider.trim() === "")) {
|
|
651
652
|
const named = namedProvider(provider);
|
|
652
653
|
if (heldElsewhere(host.startOwner, named))
|
|
653
654
|
throw heldBy(host.startOwner, named);
|
|
@@ -656,10 +657,6 @@ export function createConversationStore(host, registry) {
|
|
|
656
657
|
const startable = (isRootFolder(folder) ? registry().names.filter((name) => registry().get(name).routesAtRoot === true) : registry().names).filter((name) => !heldElsewhere(host.startOwner, name));
|
|
657
658
|
if (startable.length === 0)
|
|
658
659
|
throw new GatewayError(409, `every agent CLI this owner could start in ${folder} is started by the other owner now: ${heldBy(host.startOwner, "each").message}`, { owner: host.startOwner });
|
|
659
|
-
if (startable.length === 1) {
|
|
660
|
-
process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${startable[0]}, the one CLI that routes from there\n`);
|
|
661
|
-
return { provider: startable[0] };
|
|
662
|
-
}
|
|
663
660
|
let rooms;
|
|
664
661
|
let unreadBecause;
|
|
665
662
|
try {
|
|
@@ -672,7 +669,12 @@ export function createConversationStore(host, registry) {
|
|
|
672
669
|
rooms = autoSwitch.unreadRooms(err.message);
|
|
673
670
|
unreadBecause = err.message;
|
|
674
671
|
}
|
|
675
|
-
const picked = autoSwitch.autoProvider(registry().names, rooms, startable
|
|
672
|
+
const picked = autoSwitch.autoProvider(registry().names, rooms, startable, {
|
|
673
|
+
home: homedir(),
|
|
674
|
+
usesKey: (name) => registry().get(name)?.usesKey?.(folder) ?? false,
|
|
675
|
+
});
|
|
676
|
+
if (picked === undefined)
|
|
677
|
+
throw new GatewayError(503, "Auto has no subscription with room and no permitted, funded key for the eligible CLIs.");
|
|
676
678
|
const unread = [...new Set(Object.values(rooms).flatMap((r) => (r?.state === "unread" ? [r.reason] : [])))];
|
|
677
679
|
const words = Object.entries(rooms).map(([id, r]) => `${id} ${r?.state}`).join(", ") + (unread.length === 0 ? "" : ` — unread: ${unread.join("; ")}`);
|
|
678
680
|
process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick over ${words}\n`);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* model's 128000 limit (probe, #2059) — the turn cannot reach the model at all.
|
|
13
13
|
*/
|
|
14
14
|
import { createHash } from "crypto";
|
|
15
|
-
import { existsSync, readFileSync, readdirSync } from "fs";
|
|
15
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "fs";
|
|
16
16
|
import { homedir } from "os";
|
|
17
17
|
import { join } from "path";
|
|
18
18
|
import { LoggedCliSession, folderKey, logRow } from "./cliSession.js";
|
|
@@ -22,6 +22,31 @@ export function createCopilotDriver(runtime) {
|
|
|
22
22
|
function stateDir(name) {
|
|
23
23
|
return join(runtime.configDir, "agent", "copilot", createHash("sha256").update(name).digest("hex").slice(0, 16));
|
|
24
24
|
}
|
|
25
|
+
function userCopilotDir() {
|
|
26
|
+
return join(process.env.XDG_CONFIG_HOME || homedir(), ".copilot");
|
|
27
|
+
}
|
|
28
|
+
/** The selected provider must be one of the external providers in the configuration this child inherits. */
|
|
29
|
+
function usesKey() {
|
|
30
|
+
const config = userCopilotDir();
|
|
31
|
+
const settings = join(config, "settings.json");
|
|
32
|
+
const providers = join(config, "providers.json");
|
|
33
|
+
if (!existsSync(settings) || !existsSync(providers))
|
|
34
|
+
return false;
|
|
35
|
+
const model = JSON.parse(readFileSync(settings, "utf8")).model;
|
|
36
|
+
if (typeof model !== "string" || !model.includes("/"))
|
|
37
|
+
return false;
|
|
38
|
+
const named = model.split("/", 1)[0];
|
|
39
|
+
return (JSON.parse(readFileSync(providers, "utf8")).providers ?? []).some((provider) => provider.name === named);
|
|
40
|
+
}
|
|
41
|
+
const SEEDED_USER_FILES = ["config.json", "settings.json", "providers.json"];
|
|
42
|
+
function seedFromUser(configDir) {
|
|
43
|
+
mkdirSync(configDir, { recursive: true });
|
|
44
|
+
for (const name of SEEDED_USER_FILES) {
|
|
45
|
+
const from = join(userCopilotDir(), name);
|
|
46
|
+
if (existsSync(from))
|
|
47
|
+
copyFileSync(from, join(configDir, name));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
25
50
|
/**
|
|
26
51
|
* Whether the person has trusted this folder, or one above it, in the CLI's own "Do you trust the files in this
|
|
27
52
|
* folder?" — read from the CLI's user config (`$XDG_CONFIG_HOME/.copilot`, else `~/.copilot`), never written. The CLI
|
|
@@ -29,7 +54,7 @@ export function createCopilotDriver(runtime) {
|
|
|
29
54
|
* a folder not on it, so a turn is never typed into a CLI that would ask it.
|
|
30
55
|
*/
|
|
31
56
|
function folderTrusted(folder) {
|
|
32
|
-
const file = join(
|
|
57
|
+
const file = join(userCopilotDir(), "config.json");
|
|
33
58
|
if (!existsSync(file))
|
|
34
59
|
return false;
|
|
35
60
|
const config = JSON.parse(readFileSync(file, "utf8").split(/\r?\n/).filter((line) => !line.trimStart().startsWith("//")).join("\n"));
|
|
@@ -140,10 +165,12 @@ export function createCopilotDriver(runtime) {
|
|
|
140
165
|
name: "copilot",
|
|
141
166
|
label: "Copilot",
|
|
142
167
|
command: "copilot",
|
|
168
|
+
usesKey,
|
|
143
169
|
nativeArgs: (model) => model ? ["--model", model] : [],
|
|
144
170
|
refusal: (project, _model, cli) => folderTrusted(project) ? nativeCliRefusal("copilot", project, cli) : `Copilot has not been trusted in ${project}, so its CLI would stop on "Do you trust the files in this folder?" before reading any message — run copilot in that folder once and answer "Yes, and remember this folder for future sessions", then send the message again`,
|
|
145
171
|
open: (spec) => {
|
|
146
172
|
const configDir = stateDir(spec.name ?? spec.sessionId);
|
|
173
|
+
seedFromUser(configDir);
|
|
147
174
|
return Object.assign(new LoggedCliSession(spec, copilotCli(configDir), runtime), { storePath: join(configDir, "session-state") });
|
|
148
175
|
},
|
|
149
176
|
};
|