toolroll 0.9.116 → 0.9.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +93 -16
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +12 -2
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
@@ -21,7 +21,13 @@ import { packageVersion } from "../monitoring.js";
21
21
  import { readChildWindow } from "../live-children-read.js";
22
22
  import { readMainWindow } from "../live-main-read.js";
23
23
  import { runLiveCommands } from "../store.js";
24
- import { agentsReadOf, resultDiffContextOf, resultDiffFileOf, resultDiffOf, resultRunsOf, stepCardsOf } from "../engine-reads.js";
24
+ import { agentsReadOf, resultDiffContextOf, resultDiffFileOf, resultDiffOf, resultRunsOf, stepCardsOf, taskResultOf } from "../engine-reads.js";
25
+ import { leadChatOf } from "../engine-chat.js";
26
+ import { remoteAllows } from "../operate-remote.js";
27
+ import { verifyApproverStanding } from "../principal.js";
28
+ import { admitRemoteTerminalRequest, isRemoteTerminalRequest, sendTerminalConnectionRefusal } from "../terminal-connection.js";
29
+ import { leadNameOf } from "../lead-identity.js";
30
+ import { NOT_STARTED_SESSION } from "./render-chat.js";
25
31
  import { handlersOf } from "./handler-registry.js";
26
32
  import { matchTaskPath, respond } from "./http.js";
27
33
  import { rereadBrowser } from "./live.js";
@@ -33,12 +39,23 @@ const sendChecked = (response, status, name, value) => json(response, status, ch
33
39
  const refusal = (response, status, error) => sendChecked(response, status, "refusal", { error });
34
40
  export function readRunLive(runtime, request, who, runId, file, cursor, key) {
35
41
  const { store, options } = runtime;
42
+ const clock = runtime.clock ?? (() => new Date());
36
43
  const allowed = () => {
37
- if (rereadBrowser(runtime, request, who) === null)
38
- return false;
39
- const run = store.getRun(runId);
40
- const repo = run === null ? null : runtime.taskRepoOf(run.taskRef);
41
- return run !== null && repo !== null && runtime.runVisible(run) && store.accountCanAccess(who.name, repo);
44
+ if (who.via === "cookie") {
45
+ if (rereadBrowser(runtime, request, who) === null)
46
+ return false;
47
+ const run = store.getRun(runId);
48
+ const repo = run === null ? null : runtime.taskRepoOf(run.taskRef);
49
+ return run !== null && repo !== null && runtime.runVisible(run) && store.accountCanAccess(who.name, repo);
50
+ }
51
+ if (who.via === "bearer" && who.principal !== undefined && isRemoteTerminalRequest(request)) {
52
+ if (!admitRemoteTerminalRequest(request, store, who.principal, clock).ok)
53
+ return false;
54
+ const run = store.getRun(runId);
55
+ const repo = run === null ? null : runtime.taskRepoOf(run.taskRef);
56
+ return run !== null && repo !== null && runtime.runVisible(run) && remoteAllows(store, who.principal, repo);
57
+ }
58
+ return false;
42
59
  };
43
60
  if (!allowed())
44
61
  return { ok: false };
@@ -93,15 +110,22 @@ export function createEngineHandlers(runtime) {
93
110
  }
94
111
  async function liveRun(ctx) {
95
112
  const { url, who, request, response } = ctx;
96
- if (who.via !== "cookie")
113
+ const remote = who.via === "bearer" && who.principal !== undefined && isRemoteTerminalRequest(request);
114
+ if (who.via !== "cookie" && !remote)
97
115
  return refusal(response, 403, "session");
98
116
  const query = liveQueryOf(url);
99
117
  if (query === null)
100
118
  return refusal(response, 400, "request");
101
119
  const runId = Number(url.pathname.slice("/agents/live/run/".length));
102
120
  const read = readRunLive(runtime, request, who, runId, query.file, query.cursor, cursorKey);
103
- if (!read.ok)
121
+ if (!read.ok) {
122
+ if (remote && who.via === "bearer" && who.principal !== undefined) {
123
+ const check = admitRemoteTerminalRequest(request, store, who.principal, clock);
124
+ if (!check.ok)
125
+ return sendTerminalConnectionRefusal(request, response, check.status, check.error);
126
+ }
104
127
  return refusal(response, 404, "run");
128
+ }
105
129
  const ref = store.refForId(read.run.taskRef);
106
130
  const body = {
107
131
  version: ENGINE_API_VERSION,
@@ -273,13 +297,23 @@ export function createEngineHandlers(runtime) {
273
297
  return family === null || family.problem !== null ? null : family;
274
298
  }
275
299
  async function taskSteps(ctx) {
276
- const { url, response, who } = ctx;
277
- if ([...url.searchParams.keys()].length > 0)
300
+ const { url, request, response, who } = ctx;
301
+ const keys = [...url.searchParams.keys()];
302
+ const withChoices = url.searchParams.get("choices") === "1";
303
+ if (keys.some(key => key !== "choices") || keys.length > 1 || (keys.length === 1 && !withChoices))
278
304
  return refusal(response, 400, "request");
279
305
  const family = familyAt(url, "steps");
280
306
  if (family === null)
281
307
  return refusal(response, 404, "task");
282
- return sendChecked(response, 200, "stepCards", stepCardsOf({ store, family, now: clock(), access: runtime.workAccess(), evidenceRoot, viewer: who.name }));
308
+ const payload = stepCardsOf({ store, family, now: clock(), access: runtime.workAccess(), evidenceRoot, viewer: who.name, withChoices });
309
+ if (who.via === "bearer" && who.principal !== undefined && isRemoteTerminalRequest(request)) {
310
+ const after = admitRemoteTerminalRequest(request, store, who.principal, clock);
311
+ if (!after.ok)
312
+ return sendTerminalConnectionRefusal(request, response, after.status, after.error);
313
+ if (familyAt(url, "steps") === null)
314
+ return refusal(response, 404, "task");
315
+ }
316
+ return sendChecked(response, 200, "stepCards", payload);
283
317
  }
284
318
  async function taskApproval(ctx) {
285
319
  const { url, response, who, request } = ctx;
@@ -287,7 +321,9 @@ export function createEngineHandlers(runtime) {
287
321
  return refusal(response, 403, "session");
288
322
  if (!runtime.browserKeys.terminalKeyed(who, request))
289
323
  return refusal(response, 403, "key");
290
- if ([...url.searchParams.keys()].length > 0)
324
+ const paramKeys = [...url.searchParams.keys()];
325
+ const allowStepUp = paramKeys.length === 1 && paramKeys[0] === "stepup" && url.searchParams.get("stepup") === "1";
326
+ if (paramKeys.length > 0 && !allowStepUp)
291
327
  return refusal(response, 400, "request");
292
328
  const family = familyAt(url, "approval");
293
329
  if (family === null)
@@ -300,13 +336,31 @@ export function createEngineHandlers(runtime) {
300
336
  return refusal(response, 404, "task");
301
337
  if (!waits(view))
302
338
  return none(NOTHING_TO_APPROVE);
303
- if (view.approvalLocal?.eligible !== true)
304
- return none(`${view.approvalLocal?.eligible === false ? `${view.approvalLocal.message} ` : "This approval needs your password. "}${APPROVE_IN_BROWSER}`);
339
+ if (view.approvalLocal?.eligible !== true) {
340
+ if (!allowStepUp) {
341
+ return none(`${view.approvalLocal?.eligible === false ? `${view.approvalLocal.message} ` : "This approval needs your password. "}${APPROVE_IN_BROWSER}`);
342
+ }
343
+ const passwordSet = runtime.store.accountOf(who.name)?.passwordSet === true;
344
+ const problem = !passwordSet
345
+ ? "Set a password to approve this."
346
+ : view.approvalFresh !== null
347
+ ? null
348
+ : "Enter your password to approve.";
349
+ return sendChecked(response, 200, "approvalCard", {
350
+ version: ENGINE_API_VERSION,
351
+ task: taskId,
352
+ key: view.approvalSummary.key,
353
+ digest: view.approvalDigest,
354
+ nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest),
355
+ terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null),
356
+ problem,
357
+ });
358
+ }
305
359
  return sendChecked(response, 200, "approvalCard", { version: ENGINE_API_VERSION, task: taskId, key: view.approvalSummary.key, digest: view.approvalDigest,
306
360
  nonce: runtime.heldApprovalNonce(who.name, taskId, view.approvalDigest), terms: approvalTermsOf(view.approvalSummary, view.planContract ?? null, view.revision ?? null), problem: null });
307
361
  }
308
362
  async function taskDiff(ctx) {
309
- const { url, response } = ctx;
363
+ const { url, request, response, who } = ctx;
310
364
  const params = url.searchParams, runParam = params.get("run"), fileParam = params.get("file"), fromParam = params.get("from"), countParam = params.get("count");
311
365
  if ([...params.keys()].some(key => key !== "run" && key !== "file" && key !== "from" && key !== "count")
312
366
  || ["run", "file", "from", "count"].some(key => params.getAll(key).length > 1)
@@ -323,15 +377,60 @@ export function createEngineHandlers(runtime) {
323
377
  const run = runParam === null ? results[0] ?? null : results.find(one => one.id === Number(runParam)) ?? null;
324
378
  if (runParam !== null && run === null)
325
379
  return refusal(response, 404, "run");
326
- if (fileParam === null)
327
- return sendChecked(response, 200, "resultDiff", resultDiffOf(store, evidenceRoot, family.root.id, run));
380
+ const remoteRecheck = () => {
381
+ if (!(who.via === "bearer" && who.principal !== undefined && isRemoteTerminalRequest(request)))
382
+ return true;
383
+ const after = admitRemoteTerminalRequest(request, store, who.principal, clock);
384
+ if (!after.ok) {
385
+ sendTerminalConnectionRefusal(request, response, after.status, after.error);
386
+ return false;
387
+ }
388
+ if (familyAt(url, "diff") === null) {
389
+ refusal(response, 404, "task");
390
+ return false;
391
+ }
392
+ return true;
393
+ };
394
+ if (fileParam === null) {
395
+ const payload = resultDiffOf(store, evidenceRoot, family.root.id, run);
396
+ return remoteRecheck() ? sendChecked(response, 200, "resultDiff", payload) : undefined;
397
+ }
328
398
  if (fromParam !== null && countParam !== null) {
329
399
  const context = resultDiffContextOf(store, evidenceRoot, family.root.id, run, Number(fileParam), Number(fromParam), Number(countParam), runtime.taskRepoOf(run.taskRef));
400
+ if (!remoteRecheck())
401
+ return;
330
402
  return context === null ? refusal(response, 404, "file") : sendChecked(response, 200, "resultDiffContext", context);
331
403
  }
332
404
  const one = resultDiffFileOf(store, evidenceRoot, family.root.id, run, Number(fileParam));
405
+ if (!remoteRecheck())
406
+ return;
333
407
  return one === null ? refusal(response, 404, "file") : sendChecked(response, 200, "resultDiffFile", one);
334
408
  }
409
+ async function taskResult(ctx) {
410
+ const { url, request, response, who } = ctx;
411
+ const params = url.searchParams, runParam = params.get("run");
412
+ if ([...params.keys()].some(key => key !== "run")
413
+ || params.getAll("run").length > 1
414
+ || (runParam !== null && !/^[1-9][0-9]{0,14}$/.test(runParam))) {
415
+ return refusal(response, 400, "request");
416
+ }
417
+ const family = familyAt(url, "result");
418
+ if (family === null)
419
+ return refusal(response, 404, "task");
420
+ const results = resultRunsOf(store, family).filter(run => runtime.runVisible(run));
421
+ const run = runParam === null ? results[0] ?? null : results.find(one => one.id === Number(runParam)) ?? null;
422
+ if (runParam !== null && run === null)
423
+ return refusal(response, 404, "run");
424
+ const payload = taskResultOf(store, evidenceRoot, family, run);
425
+ if (who.via === "bearer" && who.principal !== undefined && isRemoteTerminalRequest(request)) {
426
+ const after = admitRemoteTerminalRequest(request, store, who.principal, clock);
427
+ if (!after.ok)
428
+ return sendTerminalConnectionRefusal(request, response, after.status, after.error);
429
+ if (familyAt(url, "result") === null)
430
+ return refusal(response, 404, "task");
431
+ }
432
+ return sendChecked(response, 200, "taskResult", payload);
433
+ }
335
434
  async function redeemLink(ctx) {
336
435
  const { request, response } = ctx;
337
436
  response.setHeader("Pragma", "no-cache");
@@ -369,7 +468,8 @@ export function createEngineHandlers(runtime) {
369
468
  const id = randomBytes(32).toString("hex"), csrf = randomBytes(32).toString("hex");
370
469
  if (!saveLinkSession(runtime, request, admitted.held, "terminal", { id, csrf, keys: fields }))
371
470
  return refusal(response, 410, "used");
372
- const body = { version: ENGINE_API_VERSION, account: admitted.held.account, cookie: { name: SESSION_COOKIE, value: id }, csrf, key, epoch: runtime.keyEpoch };
471
+ const body = { version: ENGINE_API_VERSION, account: admitted.held.account, cookie: { name: SESSION_COOKIE, value: id }, csrf, key, epoch: runtime.keyEpoch,
472
+ passwordSet: runtime.store.accountOf(admitted.held.account)?.passwordSet === true };
373
473
  return sendChecked(response, 200, "linkRedemption", body);
374
474
  }
375
475
  const sessionHeld = (who, flexible, id) => {
@@ -415,7 +515,8 @@ export function createEngineHandlers(runtime) {
415
515
  held, launcher });
416
516
  if (!sent.ok)
417
517
  return acted(response, 409, "refused", sent.message);
418
- return json(response, 200, { outcome: "done", words: sent.replayed ? "That reply was already sent." : sent.fresh ? `Sent. Turn ${sent.seq} started with a fresh agent: it doesn't remember earlier turns.` : `Sent. Turn ${sent.seq} started.`,
518
+ const again = sent.resent === undefined ? "" : `Your earlier send (turn ${sent.resent.seq}) never reached the agent${sent.resent.detail === null ? "" : ` (${sent.resent.detail.slice(0, 200)})`}, so it was sent again. `;
519
+ return json(response, 200, { outcome: "done", words: again + (sent.replayed ? "That reply was already sent." : sent.fresh ? `Sent. Turn ${sent.seq} started with a fresh agent: it doesn't remember earlier turns.` : `Sent. Turn ${sent.seq} started.`),
419
520
  turn: sent.turn });
420
521
  }
421
522
  const threadClose = (act) => async (ctx) => {
@@ -519,6 +620,103 @@ export function createEngineHandlers(runtime) {
519
620
  return acted(response, 409, "refused", sent.message);
520
621
  return acted(response, 200, "done", `Sent back. Turn ${sent.seq} started${sent.fresh ? " with a fresh agent: it doesn't remember earlier turns" : ""}.`);
521
622
  }
623
+ async function leadChat(ctx) {
624
+ const { url, who, request, response, now } = ctx;
625
+ const remote = who.via === "bearer" && who.principal !== undefined && isRemoteTerminalRequest(request);
626
+ if (who.via !== "cookie" && !remote)
627
+ return refusal(response, 403, "session");
628
+ const keys = [...url.searchParams.keys()];
629
+ const projectValues = url.searchParams.getAll("project");
630
+ if (keys.some(k => k !== "project") || projectValues.length > 1)
631
+ return refusal(response, 400, "request");
632
+ const proveCaller = () => {
633
+ if (who.via === "cookie")
634
+ return rereadBrowser(runtime, request, who) !== null;
635
+ return who.principal !== undefined && admitRemoteTerminalRequest(request, store, who.principal, clock).ok;
636
+ };
637
+ if (!proveCaller())
638
+ return refusal(response, 403, "session");
639
+ let chatProject = null;
640
+ if (projectValues.length === 1 && projectValues[0] !== "") {
641
+ const wanted = projectValues[0];
642
+ if (!runtime.visible(wanted) || !runtime.managedRepos().includes(wanted))
643
+ return refusal(response, 404, "project");
644
+ chatProject = wanted;
645
+ }
646
+ const room = chatProject === null ? "chat" : `chat?project=${encodeURIComponent(chatProject)}`;
647
+ const leadName = leadNameOf(store, who.name);
648
+ const enabled = runtime.chatEnablement();
649
+ const resolvePrincipal = () => {
650
+ if (who.via === "cookie")
651
+ return who.role === "approver" ? runtime.leadPrincipal(who) : null;
652
+ if (who.principal === undefined)
653
+ return null;
654
+ const account = store.accountOf(who.name);
655
+ if (account === null || account.role !== "approver")
656
+ return null;
657
+ const allowedRepos = runtime.managedRepos().filter(repo => remoteAllows(store, who.principal, repo));
658
+ const verified = verifyApproverStanding(store, who.name, who.generation, allowedRepos);
659
+ return verified.ok ? verified.who : null;
660
+ };
661
+ const principal = resolvePrincipal();
662
+ if (!enabled.ok || principal === null) {
663
+ const problem = !enabled.ok ? enabled.why : "Sign in as an approver to chat with the Lead.";
664
+ return sendChecked(response, 200, "leadChat", {
665
+ version: ENGINE_API_VERSION,
666
+ room,
667
+ session: null,
668
+ leadName,
669
+ canSend: false,
670
+ problem,
671
+ project: chatProject,
672
+ busy: false,
673
+ pendingProposals: 0,
674
+ queued: [],
675
+ messages: [],
676
+ });
677
+ }
678
+ const found = store.activeLeadSession(who.name, enabled.credentialKey);
679
+ const notStarted = enabled.billing === "subscription" && (found === null || found.ceilingDigest !== principal.ceilingDigest);
680
+ const ceilingStale = !notStarted && found !== null && found.ceilingDigest !== principal.ceilingDigest;
681
+ const session = notStarted
682
+ ? NOT_STARTED_SESSION
683
+ : found !== null && !ceilingStale && found.approverGeneration === principal.generation
684
+ ? found.id
685
+ : null;
686
+ const canSend = !remote && session !== null;
687
+ const rows = runtime.leadConversationRows(who, principal, null, now, chatProject);
688
+ if (!proveCaller() || resolvePrincipal() === null) {
689
+ if (remote && who.via === "bearer" && who.principal !== undefined) {
690
+ const check = admitRemoteTerminalRequest(request, store, who.principal, clock);
691
+ if (!check.ok)
692
+ return sendTerminalConnectionRefusal(request, response, check.status, check.error);
693
+ }
694
+ return refusal(response, 403, "session");
695
+ }
696
+ const problem = remote
697
+ ? "Remote Lead chat is read-only here — press w to open Lead in the browser."
698
+ : ceilingStale
699
+ ? "Project access changed. Start a new conversation in the browser to continue."
700
+ : !canSend
701
+ ? "Start a Lead conversation in the browser first."
702
+ : notStarted ? null : rows.failure ?? null;
703
+ return sendChecked(response, 200, "leadChat", leadChatOf({
704
+ room,
705
+ session,
706
+ leadName,
707
+ canSend,
708
+ problem,
709
+ project: chatProject,
710
+ messages: rows.messages,
711
+ proposals: rows.proposals,
712
+ decisions: rows.decisions,
713
+ pending: rows.pending,
714
+ ask: rows.ask,
715
+ staleAsk: rows.staleAsk,
716
+ asks: rows.asks,
717
+ queue: rows.queue,
718
+ }));
719
+ }
522
720
  return {
523
721
  upkeep: () => {
524
722
  if (!tidying) {
@@ -557,9 +755,9 @@ export function createEngineHandlers(runtime) {
557
755
  }
558
756
  },
559
757
  registrations: [
560
- ...handlersOf("pages", { "engine.hello": hello, "engine.agents": agents, "engine.agents-check": agentsCheck, "agents.live.run": liveRun, "agents.live.thread": liveThread, "agents.live.threads": liveThreads,
758
+ ...handlersOf("pages", { "engine.hello": hello, "engine.agents": agents, "engine.agents-check": agentsCheck, "engine.chat": leadChat, "agents.live.run": liveRun, "agents.live.thread": liveThread, "agents.live.threads": liveThreads,
561
759
  "agents.live.thread.answer": threadAnswer, "agents.live.thread.start": threadStart, "agents.live.thread.turn": threadTurn, "agents.live.thread.stop": threadClose("stop"), "agents.live.thread.end": threadClose("end"), "agents.live.thread.ship": threadShip, "agents.live.thread.ship-cancel": threadShipCancel, "agents.live.thread.ship-send-back": threadShipSendBack }),
562
- ...handlersOf("tasks", { "task.steps": taskSteps, "task.approval": taskApproval, "task.diff": taskDiff }),
760
+ ...handlersOf("tasks", { "task.steps": taskSteps, "task.approval": taskApproval, "task.diff": taskDiff, "task.result": taskResult }),
563
761
  ...handlersOf("people", {}, { "edge.login-link-json": redeemLink }),
564
762
  ],
565
763
  };
@@ -20,7 +20,9 @@ import { saveScript } from "../flow-scripts.js";
20
20
  import { chooseFlowCard } from "../flow-send.js";
21
21
  import { exportFlow, fetchFlowFile, FlowFileError, importFlow, parseFlowFile, planFlowImport } from "../flow-share.js";
22
22
  import { addFlowTriggerTo, checkFlowTriggerNow, pressFlowButton, removeFlowTrigger, removeLinearKey, setFlowTriggerOn, renewFlowHook, saveHooksBase, saveLinearKey, saveSigningSecret, setUpFlowHook, changeFlowHookSender, setFlowHookScope, shareFlowButton, stopSharingFlowButton, rawTakesDeliveries, rawAdmitsAnyone } from "../flow-triggers.js";
23
- import { FLOW_IMPORT_SCRIPT, flowFallbackHtml, flowImportHtml, flowsListHtml, flowView } from "../flows-ui.js";
23
+ import { automationsOf, FLOW_IMPORT_SCRIPT, flowFallbackHtml, flowImportHtml, flowsListHtml, flowView } from "../flows-ui.js";
24
+ import { checkEngineResponse, ENGINE_API_VERSION } from "../contracts/engine-api.js";
25
+ import { localActNow, localOwnerRefusal } from "../local-owner.js";
24
26
  import { FLOW_TEMPLATES, FlowContractError, validateFlowDefinition, withZoneNames } from "../flows.js";
25
27
  import { revokeFlowBrowser, signFlowBrowser } from "../flow-browser.js";
26
28
  import { prepareUnattendedCandidates, parseUnattendedAsk, revokeUnattended, signUnattended, untilWords } from "../flow-unattended.js";
@@ -132,6 +134,14 @@ export function createFlowsHandlers(runtime) {
132
134
  const flows = store.listFlows(projects);
133
135
  return sendScreen(response, 200, screen("Flows", flowsListHtml(store, flows, projects, who.via === "cookie" && who.role === "approver", url.searchParams.get("problem"), url.searchParams.get("project"), clock()), { chrome: chromeFor(project, "flows"), functional: { script: FLOW_IMPORT_SCRIPT } }));
134
136
  }
137
+ async function automationsRead(ctx) {
138
+ const { url, who, response } = ctx;
139
+ if ([...url.searchParams.keys()].length > 0)
140
+ return sendJson(response, 400, checkEngineResponse("refusal", { error: "request" }));
141
+ response.setHeader("cache-control", "no-store");
142
+ return sendJson(response, 200, checkEngineResponse("automations", { version: ENGINE_API_VERSION, canAct: who.via === "cookie" && who.role === "approver",
143
+ automations: automationsOf(store, store.listFlows(consoleProjects()), clock()) }));
144
+ }
135
145
  async function flowInsightsRead(ctx) {
136
146
  const { url, response } = ctx;
137
147
  const flow = visibleFlow(Number(pathPart(url, 2)));
@@ -537,11 +547,12 @@ export function createFlowsHandlers(runtime) {
537
547
  }
538
548
  return page(plan, null, 200);
539
549
  }
540
- function openFlowChange(ctx) {
550
+ function openFlowChange(ctx, inPlace = false) {
541
551
  const { url, who, response, posted } = ctx;
542
552
  const body = readForm(posted, CONSOLE_FORMS.flows);
543
553
  const now = clock();
544
- const answer = (status, payload) => sendJson(response, status, payload);
554
+ const answer = (status, payload) => sendJson(response, status, !inPlace ? payload
555
+ : { outcome: status < 400 && payload["ok"] === true ? "done" : "refused", words: typeof payload["said"] === "string" ? payload["said"] : "" });
545
556
  const projects = consoleProjects();
546
557
  const flow = visibleFlow(Number(pathPart(url, 2)));
547
558
  if (flow === null) {
@@ -556,9 +567,9 @@ export function createFlowsHandlers(runtime) {
556
567
  advanceFlows(store, flow.repo, now, { evidenceRoot });
557
568
  }
558
569
  catch { }
559
- return answer(200, { ok: true, said, view: viewNow(), ...extra });
570
+ return answer(200, inPlace ? { ok: true, said } : { ok: true, said, view: viewNow(), ...extra });
560
571
  };
561
- return { body, now, answer, projects, flow, definition, dir, viewNow, settle };
572
+ return { body, now, answer, projects, flow, definition, dir, viewNow, settle, inPlace };
562
573
  }
563
574
  const flowAct = (action) => async (ctx) => {
564
575
  const { who, response } = ctx;
@@ -726,17 +737,36 @@ export function createFlowsHandlers(runtime) {
726
737
  const cancelled = cancelFlowCard(store, target, who.name, now);
727
738
  return cancelled.ok ? settle(cancelled.said) : answer(409, { ok: false, said: cancelled.message });
728
739
  };
740
+ const LOCAL_TRIGGER_ACTS = { pause: "trigger-pause", resume: "trigger-resume", check: "trigger-run", press: "trigger-run" };
729
741
  const triggerAct = (verb) => async (ctx) => {
730
742
  const { url, who } = ctx;
731
- const change = openFlowChange(ctx);
743
+ const localAct = LOCAL_TRIGGER_ACTS[verb];
744
+ const change = openFlowChange(ctx, localAct !== undefined && requestContext.getStore()?.terminalAct === true);
732
745
  if (change === null)
733
746
  return;
734
- const { body, now, answer, flow, dir, viewNow, settle } = change;
747
+ const { body, now, answer, flow, dir, viewNow, settle, inPlace } = change;
735
748
  const trigger = store.getFlowTrigger(Number(pathPart(url, 4)));
736
749
  if (trigger === null || trigger.flow !== flow.id || trigger.state === "removed")
737
750
  return answer(404, { ok: false, said: "That trigger isn't on this flow." });
751
+ const localOwner = who.via === "cookie" && who.authority !== "full";
752
+ const ownerStands = () => !localOwner || (localAct !== undefined && localActNow(store, localAct) !== null);
753
+ const ownerRefused = () => answer(403, { ok: false, said: localOwnerRefusal(store.accountOf(who.name)?.passwordSet === true, `/flows/${flow.id}`).message });
754
+ if (!ownerStands())
755
+ return ownerRefused();
738
756
  if (verb === "pause" || verb === "resume") {
739
- setFlowTriggerOn(store, trigger, verb === "resume", now, who.name);
757
+ const done = store.transact(() => {
758
+ const current = store.getFlowTrigger(trigger.id);
759
+ if (current === null || current.flow !== flow.id || current.state === "removed")
760
+ return "gone";
761
+ if (!ownerStands())
762
+ return "refused";
763
+ setFlowTriggerOn(store, current, verb === "resume", now, who.name);
764
+ return "done";
765
+ });
766
+ if (done === "gone")
767
+ return answer(404, { ok: false, said: "That trigger isn't on this flow." });
768
+ if (done === "refused")
769
+ return ownerRefused();
740
770
  return settle(verb === "pause" ? "Trigger paused." : "Trigger on again.");
741
771
  }
742
772
  if (verb === "remove") {
@@ -766,7 +796,9 @@ export function createFlowsHandlers(runtime) {
766
796
  catch {
767
797
  answers = [];
768
798
  }
769
- const pressed = pressFlowButton(store, trigger, Array.isArray(answers) ? answers : [], who.name, now);
799
+ const pressed = store.transact(() => ownerStands() ? pressFlowButton(store, trigger, Array.isArray(answers) ? answers : [], who.name, now) : null);
800
+ if (pressed === null)
801
+ return ownerRefused();
770
802
  return pressed.ok ? settle(pressed.said) : answer(400, { ok: false, said: pressed.message });
771
803
  }
772
804
  if (verb === "check") {
@@ -776,7 +808,7 @@ export function createFlowsHandlers(runtime) {
776
808
  advanceFlows(store, flow.repo, now, { evidenceRoot });
777
809
  }
778
810
  catch { }
779
- return answer(checked.ok ? 200 : 409, { ok: checked.ok, said: checked.said, view: viewNow() });
811
+ return answer(checked.ok ? 200 : 409, inPlace ? { ok: checked.ok, said: checked.said } : { ok: checked.ok, said: checked.said, view: viewNow() });
780
812
  }
781
813
  if (dir === null)
782
814
  return answer(409, { ok: false, said: "Webhook secrets are kept on the console's computer." });
@@ -902,6 +934,7 @@ export function createFlowsHandlers(runtime) {
902
934
  "flows.new": newFlowGallery,
903
935
  "flows.gallery": galleryTemplatePage,
904
936
  "flows.page": flowsPage,
937
+ "engine.automations": automationsRead,
905
938
  "kits": kitsGallery,
906
939
  "kit.page": kitPage,
907
940
  "subagents": subagentsPage,
@@ -0,0 +1,25 @@
1
+ export const FOUND_REPOS_TTL_MS = 60_000;
2
+ export const FOUND_REPOS_MAX = 40;
3
+ export const FOUND_PLACES_MAX = 6;
4
+ export function foundReposCache(clock, ttlMs = FOUND_REPOS_TTL_MS) {
5
+ let kept = null;
6
+ let running = null;
7
+ return (key, look) => {
8
+ const now = clock().getTime();
9
+ if (kept !== null && kept.key === key && now >= kept.at && now - kept.at < ttlMs)
10
+ return Promise.resolve(kept.repos);
11
+ if (running !== null && running.key === key)
12
+ return running.answer;
13
+ const answer = look().then(found => {
14
+ if (found.complete)
15
+ kept = { key, at: clock().getTime(), repos: [...found.repos] };
16
+ return found.repos;
17
+ });
18
+ const mine = { key, answer };
19
+ running = mine;
20
+ const forget = () => { if (running === mine)
21
+ running = null; };
22
+ answer.then(forget, forget);
23
+ return answer;
24
+ };
25
+ }
@@ -34,17 +34,29 @@ export function createSharedGuards(runtime) {
34
34
  return runtime.store.isInstanceOperator(actor.name) && runtime.store.accountOf(actor.name)?.generation === actor.generation;
35
35
  }
36
36
  const restricted = () => {
37
- const actor = requestContext.getStore()?.actor;
38
- return actor !== undefined && runtime.store.accountOf(actor)?.projects !== null;
37
+ const facts = requestContext.getStore(), actor = facts?.actor;
38
+ return actor !== undefined && (runtime.store.accountOf(actor)?.projects !== null || (facts?.tokenProjects !== undefined && facts.tokenProjects !== null));
39
39
  };
40
40
  const visible = (repo) => {
41
- const actor = requestContext.getStore()?.actor;
41
+ const facts = requestContext.getStore(), actor = facts?.actor, tp = facts?.tokenProjects;
42
+ if (tp !== undefined && tp !== null && (repo === null || !tp.includes(repo)))
43
+ return false;
42
44
  return rowVisible(runtime.liveCeiling(), repo) && (actor === undefined || runtime.store.accountCanAccess(actor, repo));
43
45
  };
44
46
  function codingProjectAllowed(repo) { return runtime.codingProjects().includes(repo); }
45
- const admissionList = () => restricted() ? [...(runtime.store.accountOf(requestContext.getStore().actor)?.projects ?? [])].filter(visibleNow()) : runtime.unscopedMode
46
- ? null
47
- : [...new Set([...runtime.managedRepos(), ...(runtime.ceiling.roots.length === 0 ? [] : runtime.store.knownRepos().filter(visibleNow()))])];
47
+ const admissionList = () => restricted()
48
+ ? (() => {
49
+ const facts = requestContext.getStore();
50
+ const accountProjects = runtime.store.accountOf(facts.actor)?.projects ?? null;
51
+ const tp = facts.tokenProjects ?? null;
52
+ const base = tp !== null
53
+ ? (accountProjects === null ? [...tp] : tp.filter(repo => accountProjects.includes(repo)))
54
+ : [...(accountProjects ?? [])];
55
+ return base.filter(visibleNow());
56
+ })()
57
+ : runtime.unscopedMode
58
+ ? null
59
+ : [...new Set([...runtime.managedRepos(), ...(runtime.ceiling.roots.length === 0 ? [] : runtime.store.knownRepos().filter(visibleNow()))])];
48
60
  const taskRepoOf = (taskRef) => runtime.store.refForId(taskRef)?.repo ?? null;
49
61
  function authorizeMutation(request, who, body) {
50
62
  if (who.via === "bearer") {
@@ -167,6 +179,8 @@ export function createSharedGuards(runtime) {
167
179
  refuse(response, who, 403, "that project is outside this console's reach", "/projects");
168
180
  return false;
169
181
  }
182
+ if (route?.id === 'engine.chat' && request.method === 'GET' && who.via === 'bearer' && who.principal !== undefined)
183
+ return true;
170
184
  if (route?.limited === 'conversation' && request.method === 'GET' && who.via === 'cookie' && url.searchParams.get('private') !== '1' && ((!url.searchParams.has('task') && !url.searchParams.has('result')) || url.searchParams.has('conversation'))) {
171
185
  try {
172
186
  const snapshot = runtime.team.domain.snapshot({ name: who.name, generation: who.session.generation }, url.searchParams.get('conversation') ?? undefined, url.searchParams.get('lead') ?? undefined);