toolroll 0.9.116 → 0.9.117

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 (129) hide show
  1. package/CHANGELOG.md +36 -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 +39 -10
  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 +3 -1
  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/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +14 -3
  33. package/dist/contracts/engine-api.js +331 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-session.js +91 -47
  57. package/dist/flexible-ship.js +87 -7
  58. package/dist/flexible-start.js +4 -1
  59. package/dist/flexible-thread.js +2 -3
  60. package/dist/flexible-turns.js +26 -5
  61. package/dist/flow-triggers.js +13 -4
  62. package/dist/flows-ui.js +54 -20
  63. package/dist/handoff-cli.js +630 -0
  64. package/dist/invoke.js +55 -13
  65. package/dist/lead-contract.js +5 -4
  66. package/dist/lead-doors.js +80 -1
  67. package/dist/lead-progress.js +9 -0
  68. package/dist/lead-tools.js +681 -10
  69. package/dist/lead.js +37 -9
  70. package/dist/live-bus.js +11 -0
  71. package/dist/live-terminal.js +132 -12
  72. package/dist/local-handoff.js +363 -0
  73. package/dist/local-owner-acts.js +264 -2
  74. package/dist/local-owner.js +16 -1
  75. package/dist/multiplayer-handoff.js +528 -0
  76. package/dist/multiplayer-presence.js +471 -0
  77. package/dist/names.js +17 -4
  78. package/dist/needs-you.js +10 -0
  79. package/dist/operate.js +280 -19
  80. package/dist/policy.js +2 -2
  81. package/dist/project-delete-ui.js +18 -11
  82. package/dist/project-delete.js +65 -4
  83. package/dist/project-tools.js +1 -1
  84. package/dist/prompt.js +1 -1
  85. package/dist/provider-connection.js +2 -0
  86. package/dist/provider-home.js +251 -8
  87. package/dist/provider.js +3 -2
  88. package/dist/publish.js +119 -64
  89. package/dist/pull-request-flow.js +35 -14
  90. package/dist/read-executor-worker.js +1 -1
  91. package/dist/read-executor.js +95 -1
  92. package/dist/restore-retirement.js +152 -0
  93. package/dist/result-follow-ups.js +116 -37
  94. package/dist/route-change.js +44 -4
  95. package/dist/scope.js +62 -5
  96. package/dist/serve.js +49 -5
  97. package/dist/server/chat.js +94 -13
  98. package/dist/server/direct-chat.js +583 -0
  99. package/dist/server/engine-api.js +219 -21
  100. package/dist/server/flows.js +43 -10
  101. package/dist/server/found-repos.js +25 -0
  102. package/dist/server/guards.js +20 -6
  103. package/dist/server/live.js +81 -23
  104. package/dist/server/pages.js +67 -13
  105. package/dist/server/people-tokens.js +47 -6
  106. package/dist/server/remote.js +29 -0
  107. package/dist/server/render-results.js +6 -2
  108. package/dist/server/render-settings.js +4 -2
  109. package/dist/server/render-tasks.js +18 -17
  110. package/dist/server/route-table.js +69 -2
  111. package/dist/server/settings.js +22 -7
  112. package/dist/server/task-views.js +15 -3
  113. package/dist/server/tasks.js +39 -2
  114. package/dist/server/terminals.js +185 -11
  115. package/dist/settings-proofs.js +1 -1
  116. package/dist/store.js +499 -56
  117. package/dist/subscription-chat.js +33 -6
  118. package/dist/subscription-usage.js +233 -0
  119. package/dist/task-live.js +2 -1
  120. package/dist/teardown-git.js +34 -4
  121. package/dist/terminal-connection.js +159 -0
  122. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  123. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  124. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  125. package/dist/tui/linux-x64/toolroll-tui +0 -0
  126. package/dist/tui-contract.js +1 -1
  127. package/dist/tui-launch.js +32 -1
  128. package/dist/workspace-identity-schema.js +21 -0
  129. package/package.json +3 -1
package/dist/serve.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { secretFolder } from "./tool-secret-store.js";
2
+ import { pendingNetworkRequests } from "./agent-network-request.js";
3
+ import { admitRemoteTerminalRequest, isRemoteTerminalRequest, REMOTE_TUI_READ_ROUTES, sendTerminalConnectionRefusal } from "./terminal-connection.js";
2
4
  import { fallbackSettingOf } from "./fallback.js";
3
5
  import { acceptedIdentities, recoverLearning } from "./project-learning.js";
4
6
  import { consoleFolderGate, syncProjectIdentities } from "./project-identity.js";
@@ -111,6 +113,7 @@ import { instrumentRequest } from "./server-telemetry.js";
111
113
  import { createChatHandlers } from './server/chat.js';
112
114
  import { createLiveHandlers } from './server/live.js';
113
115
  import { createTerminalHandlers, terminalHostFor } from './server/terminals.js';
116
+ import { createDirectChatHandlers } from './server/direct-chat.js';
114
117
  import { declareSoloOnUpgrade, sessionStandsIn } from './install-mode.js';
115
118
  import { keepTypedFields, openProjectFor, settingsCrumbs } from './settings-kit.js';
116
119
  import { createSweepHandlers } from './server/sweeps.js';
@@ -398,7 +401,7 @@ export function createDecisionServer(options) {
398
401
  canDelete: who.via === "cookie" && store.isInstanceOperator(who.name),
399
402
  builds: projectBuildsOf(repo, who),
400
403
  access: projectAccessOf(repo),
401
- network: { setting: store.projectNetwork(repo), canChange: who.via === "cookie" && who.role === "approver" && !store.isDemo() && store.accountCanAccess(who.name, repo) },
404
+ network: { setting: store.projectNetwork(repo), canChange: who.via === "cookie" && who.role === "approver" && !store.isDemo() && store.accountCanAccess(who.name, repo), requests: pendingNetworkRequests(store, repo) },
402
405
  fallback: { setting: fallbackSettingOf(store, repo), canChange: who.via === "cookie" && who.role === "approver" && !store.isDemo() && store.accountCanAccess(who.name, repo) },
403
406
  writes: { setting: store.projectWrites(repo), canChange: who.via === "cookie" && who.role === "approver" && !store.isDemo() && store.accountCanAccess(who.name, repo) },
404
407
  sandbox: { setting: store.projectSandbox(repo), canChange: who.via === "cookie" && who.role === "approver" && !store.isDemo() && store.accountCanAccess(who.name, repo) },
@@ -733,7 +736,8 @@ export function createDecisionServer(options) {
733
736
  if (refuseBudget(admitPasswordSource(request)))
734
737
  return;
735
738
  const refusedToken = {};
736
- const who = identify(request, touch, edgeRoute?.domain === 'live', refusedToken);
739
+ const remoteTerminal = isRemoteTerminalRequest(request) && (edgeRoute?.domain === "live" || (matchedRoute?.stage === "console" && REMOTE_TUI_READ_ROUTES.has(matchedRoute.id)));
740
+ const who = identify(request, touch, edgeRoute?.domain === 'live' || remoteTerminal, refusedToken);
737
741
  timeline.mark("signed in");
738
742
  if (refusedToken.elsewhere === true && edgeRoute?.domain !== 'people') {
739
743
  request.resume();
@@ -750,6 +754,15 @@ export function createDecisionServer(options) {
750
754
  }
751
755
  if (who?.via === "bearer" && refuseBudget(admitBearer(request, who)))
752
756
  return;
757
+ if (remoteTerminal) {
758
+ if (who === null || who.via !== "bearer" || who.principal === undefined) {
759
+ return sendTerminalConnectionRefusal(request, response, 401, "unauthenticated");
760
+ }
761
+ const remoteAdmitted = admitRemoteTerminalRequest(request, store, who.principal, clock);
762
+ if (!remoteAdmitted.ok) {
763
+ return sendTerminalConnectionRefusal(request, response, remoteAdmitted.status, remoteAdmitted.error);
764
+ }
765
+ }
753
766
  if (purpose === 'prefetch' && who?.via !== 'cookie') {
754
767
  request.resume();
755
768
  return respond(response, 204, "text/plain; charset=utf-8", "");
@@ -793,6 +806,7 @@ export function createDecisionServer(options) {
793
806
  ? { localStepUp: localOwnerRefusal(false, method === "GET" ? passwordSetNext(pagePathOf(url)) : "/").href } : {}),
794
807
  reconnect: browserKeys.stale(who, method === "GET" ? safeReturn(pagePathOf(url)) : "/"),
795
808
  ...(method === "POST" && who.via === "cookie" && request.headers["x-toolroll-act"] === "in-place" && request.headers["x-toolroll-client"] === "terminal" ? { terminalAct: true } : {}),
809
+ ...(who.via === "bearer" && who.principal !== undefined ? { tokenProjects: who.principal.projects } : {}),
796
810
  };
797
811
  if (purpose !== 'prefetch')
798
812
  response.once("finish", () => keepSlowRequest(store, timeline, matchedRoute?.id ?? "unmatched", response.statusCode, clock()));
@@ -852,6 +866,13 @@ export function createDecisionServer(options) {
852
866
  if (!projectRequestAllowed(route, route.project, url, who, request, response, null))
853
867
  return;
854
868
  }
869
+ else if (remoteTerminal && who.via === 'bearer' && who.principal !== undefined) {
870
+ const recheck = admitRemoteTerminalRequest(request, store, who.principal, clock);
871
+ if (!recheck.ok)
872
+ return sendTerminalConnectionRefusal(request, response, recheck.status, recheck.error);
873
+ if (!projectRequestAllowed(route, route.project, url, who, request, response, null))
874
+ return;
875
+ }
855
876
  return withWorkReads(() => handleGet(route, url, who, request, response));
856
877
  }
857
878
  return handlePost(route, url, who, request, response, body);
@@ -955,6 +976,9 @@ export function createDecisionServer(options) {
955
976
  if (route.id === 'tasks' && !url.searchParams.has('project') && ((url.searchParams.get('scope') === 'all' && url.searchParams.getAll('scope').length === 1)
956
977
  || (url.searchParams.get('all') === '1' && url.searchParams.getAll('all').length === 1)))
957
978
  project = null;
979
+ if (route.id === 'work.rows' && who.via === 'bearer' && isRemoteTerminalRequest(request) && !url.searchParams.has('project') && request.headers['x-standing-orders-project'] === undefined) {
980
+ project = null;
981
+ }
958
982
  const facts = requestContext.getStore();
959
983
  if (facts !== undefined)
960
984
  facts.lens = project;
@@ -1132,7 +1156,7 @@ export function createDecisionServer(options) {
1132
1156
  const principal = enabled.ok ? leadPrincipal(who) : null;
1133
1157
  if (!enabled.ok || principal === null)
1134
1158
  return null;
1135
- const found = store.activeLeadSession(who.name);
1159
+ const found = store.activeLeadSession(who.name, enabled.credentialKey);
1136
1160
  const notStarted = (found === null || found.ceilingDigest !== principal.ceilingDigest) && enabled.billing === "subscription";
1137
1161
  const session = notStarted ? null : found;
1138
1162
  if (!notStarted && (session === null || session.ceilingDigest !== principal.ceilingDigest || session.approverGeneration !== principal.generation))
@@ -1807,6 +1831,7 @@ export function createDecisionServer(options) {
1807
1831
  flowRooms.close();
1808
1832
  taskRooms.close();
1809
1833
  liveHandlers.close();
1834
+ directChatHandlers.close();
1810
1835
  detachReads();
1811
1836
  liveFollower.close();
1812
1837
  void Promise.all([closeCoding(), terminalClosing.close?.().then(problem => { terminalClosing.problem = problem; }), bounded(team.close()), bounded(personalQueue.close()), bounded(leadMaintenance?.stop()), bounded(backgroundChecks?.stop()), bounded(reads?.close()), bounded(engineHandlers.close())])
@@ -1981,7 +2006,17 @@ export function createDecisionServer(options) {
1981
2006
  const pagesHandlers = createPagesHandlers(handlerRuntime, { listFor: tasksHandlers.workListFor, showOrder: tasksHandlers.showOrder });
1982
2007
  const engineHandlers = createEngineHandlers(handlerRuntime);
1983
2008
  const flowsHandlers = createFlowsHandlers(handlerRuntime);
1984
- const chatHandlers = createChatHandlers(handlerRuntime);
2009
+ let directChatHandlersRef = null;
2010
+ const chatHandlers = createChatHandlers(handlerRuntime, {
2011
+ directChatHost: () => directChatHandlersRef?.host ?? null,
2012
+ directChatStop: (owner, threadId) => directChatHandlersRef === null
2013
+ ? { ok: false, status: 503, error: "Direct Chat host is not ready." }
2014
+ : directChatHandlersRef.host.stopThread(owner, threadId),
2015
+ directChatDiff: (owner, threadId) => directChatHandlersRef === null
2016
+ ? { ok: false, status: 503, error: "Direct Chat host is not ready." }
2017
+ : directChatHandlersRef.host.inspectThreadDiff(owner, threadId),
2018
+ publishDirectChat: threadId => liveBus.publish({ revision: `dc:${threadId}:lead:${Date.now()}` }),
2019
+ });
1985
2020
  const settingsHandlers = createSettingsHandlers(handlerRuntime);
1986
2021
  const peopleHandlers = createPeopleHandlers(handlerRuntime);
1987
2022
  const remoteRuntime = {
@@ -1998,6 +2033,8 @@ export function createDecisionServer(options) {
1998
2033
  get options() { return options; },
1999
2034
  get coding() { return coding; },
2000
2035
  get codingProjects() { return codingProjects; },
2036
+ get codingActorAllowed() { return codingActorAllowed; },
2037
+ get codingProjectAllowed() { return codingProjectAllowed; },
2001
2038
  get liveCeiling() { return liveCeiling; },
2002
2039
  get clock() { return clock; },
2003
2040
  get evidenceRoot() { return evidenceRoot; },
@@ -2009,17 +2046,24 @@ export function createDecisionServer(options) {
2009
2046
  get hookContext() { return hookContext; },
2010
2047
  get teamsSourceBudget() { return teamsSourceBudget; },
2011
2048
  get teamsTenantBudget() { return teamsTenantBudget; },
2049
+ get taskRooms() { return taskRooms; },
2050
+ get terminalHost() { return () => terminals.host; },
2012
2051
  };
2013
2052
  const liveHandlers = createLiveHandlers(handlerRuntime, { bus: liveBus, workspaceRevision, chatProjectOf: chatHandlers.chatProjectOf, projectSummaryFor, projectScopeFor });
2014
2053
  liveTurnStarted = liveHandlers.turnStarted;
2015
2054
  const terminalHandlers = createTerminalHandlers(handlerRuntime, { ...terminals, bus: liveBus, allowedHost, publicOrigin, forwardedSourceOf, server,
2016
2055
  ...(options.agentCommandEnv === undefined ? {} : { agentEnv: options.agentCommandEnv }) });
2017
2056
  terminalClosing.close = terminalHandlers.close;
2057
+ const directChatHandlers = createDirectChatHandlers(handlerRuntime, {
2058
+ bus: liveBus,
2059
+ ...(options.directChatSeams === undefined ? {} : { seams: options.directChatSeams, disableLegacyImport: true }),
2060
+ });
2061
+ directChatHandlersRef = directChatHandlers;
2018
2062
  const remoteHandlers = createRemoteHandlers(remoteRuntime);
2019
2063
  const registry = createHandlerRegistry([
2020
2064
  ...tasksHandlers.registrations, ...flowsHandlers.registrations, ...chatHandlers.registrations,
2021
2065
  ...settingsHandlers.registrations, ...peopleHandlers.registrations, ...pagesHandlers.registrations,
2022
- ...remoteHandlers.registrations, ...liveHandlers.registrations, ...terminalHandlers.registrations, ...createSweepHandlers(handlerRuntime).registrations,
2066
+ ...remoteHandlers.registrations, ...liveHandlers.registrations, ...terminalHandlers.registrations, ...directChatHandlers.registrations, ...createSweepHandlers(handlerRuntime).registrations,
2023
2067
  ...createWelcomeHandlers(handlerRuntime).registrations, ...engineHandlers.registrations,
2024
2068
  ]);
2025
2069
  function dispatchConsole(route, ctx) {
@@ -11,7 +11,7 @@ import { assignmentOf, checkAssignmentAsOperator } from '../assignment.js';
11
11
  import { browserWorkActionHref } from '../browser-workspace.js';
12
12
  import { CHAT_ACTIONS, mintSharedActionReview, sharedActionPayload, sharedActionReviewPath } from '../chat-actions.js';
13
13
  import { CONSOLE_FORMS, readForm } from "../contracts/console-api.js";
14
- import { buildDataDocument, composeRequest, isSubscriptionChatProvider, parseAssistantEnvelope, performChatRequest, plausibleChatKey, priceOf, settleForPrice, TURN_WALL_CLOCK_MS, worstCaseForPrice } from "../converse.js";
14
+ import { buildDataDocument, composeRequest, isSubscriptionChatProvider, parseAssistantEnvelope, parseLeadImagesField, performChatRequest, plausibleChatKey, priceOf, settleForPrice, TURN_WALL_CLOCK_MS, worstCaseForPrice } from "../converse.js";
15
15
  import { DEMO_CHAT_SCRIPT, demoChatHtml, demoThreadHtml } from "../demo-chat.js";
16
16
  import { builderReadyFor, firstRunBuilderRepo, withDispatchDiagnoses } from "../dispatch.js";
17
17
  import { readVerifiedArtifact, scanForSecrets } from "../evidence.js";
@@ -46,14 +46,14 @@ import { chatAckPage, chatPage, NOT_STARTED_SESSION, coordinatorProposalsSection
46
46
  import {} from "./render-pages.js";
47
47
  import { completionForm, hardBlockerOf, homePhaseWords, owedAcceptanceOf, resultPanelHtml } from "./render-results.js";
48
48
  import { browserCaller, oneLineUa } from "./session.js";
49
- export function createChatHandlers(runtime) {
49
+ export function createChatHandlers(runtime, extras) {
50
50
  const { firstRunStepsNow, managedRepos, leadWords, store, options, phoneSetup, visible, liveTurns, leadSaid, evidenceRoot, clock, sessions, CHAT_CANDIDATE_TTL_MS, chatFetcher, CHAT_CANDIDATES_PER_APPROVER, chatCeilingDigest, workAccess, familyOf, firstTasks, leadPrincipal, taskChatFocus, chatScopeOf, leadConversationRows, demoLeadHere, sendScreen, chromeFor, teamBrowserReply, team, teamChatProvider, runVisible, runIsLive, resultDetailOf, pullRequestTargetOf, chatEnablement, sharedIndexPage, startLeadConversation, projectFamilyPeek, needsYouBadge, liveRefreshSeconds, chatKeyFor, chatCatalog, chatCatalogKnown, providerHome, mintApprovalNonce, checkLocalAgents, agentSignInCommand, bustBadge, authenticateApprover, revisionDestination, armTaskResume, consumeApprovalNonce } = runtime;
51
51
  async function mateStatus(ctx) {
52
52
  const { url, response, now } = ctx;
53
53
  const who = browserCaller(ctx.who);
54
- const found = store.activeLeadSession(who.name);
55
- const principal = leadPrincipal(who);
56
54
  const enabled = chatEnablement();
55
+ const found = enabled.ok ? store.activeLeadSession(who.name, enabled.credentialKey) : null;
56
+ const principal = leadPrincipal(who);
57
57
  const notStarted = principal !== null && enabled.ok && enabled.billing === "subscription" && (found === null || found.ceilingDigest !== principal.ceilingDigest);
58
58
  const session = notStarted ? null : found;
59
59
  if (principal === null || (!notStarted && (session === null || session.ceilingDigest !== principal.ceilingDigest || session.approverGeneration !== principal.generation))) {
@@ -215,7 +215,7 @@ export function createChatHandlers(runtime) {
215
215
  const enabled = chatEnablement();
216
216
  const pending = store.liveChatTurnFor(who.name);
217
217
  const latched = enabled.ok ? store.latchedChatTurns(enabled.credentialKey) : [];
218
- const leadSession = enabled.ok && who.role === "approver" ? store.activeLeadSession(who.name) : null;
218
+ const leadSession = enabled.ok && who.role === "approver" ? store.activeLeadSession(who.name, enabled.credentialKey) : null;
219
219
  const principal = enabled.ok && who.role === "approver" ? leadPrincipal(who) : null;
220
220
  const settingsView = url.searchParams.get("settings") === "1";
221
221
  const notStarted = !settingsView && enabled.ok && enabled.billing === "subscription" && principal !== null &&
@@ -698,8 +698,61 @@ export function createChatHandlers(runtime) {
698
698
  }
699
699
  const confirmIt = () => confirmLeadProposal(store, principal, id, now, { authority: who.authority, chatProvider: teamChatProvider, confirm: body.get("confirm") === "yes", via: "web", person: who.via === "cookie", evidenceRoot, ...(body.has("nonce") ? { actionReview: { nonce: body.get("nonce") ?? "", password: body.get("token") ?? "" } } : {}) });
700
700
  const proposed = store.getLeadProposal(id);
701
- const approving = proposed?.kind === "action" && sharedActionPayload(proposed.payload)?.operation === "scope_approve";
701
+ const proposedAction = proposed?.kind === "action" ? sharedActionPayload(proposed.payload) : null;
702
+ const approving = proposedAction?.operation === "scope_approve";
702
703
  const outcome = approving ? spendingOnlyOnSuccess(confirmIt, result => !result.ok || ("already" in result && result.already === true)) : confirmIt();
704
+ if (outcome.ok && proposedAction !== null && (proposedAction.operation === "direct_chat_start" || proposedAction.operation === "direct_chat_reply")) {
705
+ const host = extras?.directChatHost?.() ?? null;
706
+ if (host === null) {
707
+ const msg = "Direct Chat host is not available on this server.";
708
+ store.handle.prepare("UPDATE lead_proposal SET state = 'refused', outcome_json = ? WHERE id = ?")
709
+ .run(JSON.stringify({ ok: false, kind: "action", reason: "refused", said: msg, via: "web" }), id);
710
+ return cardJson ? cardAnswer(503, false, msg) : refuse(response, who, 503, msg, back);
711
+ }
712
+ const req = proposedAction.request;
713
+ if (proposedAction.operation === "direct_chat_start") {
714
+ const created = await host.createThread({
715
+ owner: who.name,
716
+ localGeneration: who.authority === "local-owner" ? who.session.localGeneration : null,
717
+ accountGeneration: who.session.generation,
718
+ requestId: randomBytes(16).toString("hex"),
719
+ repo: proposedAction.repo,
720
+ provider: String(req["provider"]),
721
+ modelId: String(req["model"] ?? ""),
722
+ ...(typeof req["effort"] === "string" && req["effort"] !== "" ? { effort: req["effort"] } : {}),
723
+ prompt: String(req["prompt"] ?? ""),
724
+ });
725
+ if (!created.ok) {
726
+ store.handle.prepare("UPDATE lead_proposal SET state = 'refused', outcome_json = ? WHERE id = ?")
727
+ .run(JSON.stringify({ ok: false, kind: "action", reason: "refused", said: created.error, via: "web" }), id);
728
+ return cardJson ? cardAnswer(created.status, false, created.error) : redirect(response, chatReturnWithLatest(back));
729
+ }
730
+ const said = `Started Direct Chat "${created.thread.title}".`;
731
+ const href = `/direct-chats/${encodeURIComponent(created.thread.id)}`;
732
+ store.handle.prepare("UPDATE lead_proposal SET outcome_json = ? WHERE id = ?")
733
+ .run(JSON.stringify({ ok: true, kind: "action", taskId: null, said, href, via: "web" }), id);
734
+ return cardJson ? cardAnswer(200, true, said, null) : redirect(response, chatReturnWithLatest(back));
735
+ }
736
+ else {
737
+ const chatId = String(req["chat"] ?? "");
738
+ const sent = await host.sendMessage({
739
+ owner: who.name,
740
+ threadId: chatId,
741
+ requestId: randomBytes(16).toString("hex"),
742
+ prompt: String(req["prompt"] ?? ""),
743
+ });
744
+ if (!sent.ok) {
745
+ store.handle.prepare("UPDATE lead_proposal SET state = 'refused', outcome_json = ? WHERE id = ?")
746
+ .run(JSON.stringify({ ok: false, kind: "action", reason: "refused", said: sent.error, via: "web" }), id);
747
+ return cardJson ? cardAnswer(sent.status, false, sent.error) : redirect(response, chatReturnWithLatest(back));
748
+ }
749
+ const said = "Sent follow-up message to Direct Chat.";
750
+ const href = `/direct-chats/${encodeURIComponent(chatId)}`;
751
+ store.handle.prepare("UPDATE lead_proposal SET outcome_json = ? WHERE id = ?")
752
+ .run(JSON.stringify({ ok: true, kind: "action", taskId: null, said, href, via: "web" }), id);
753
+ return cardJson ? cardAnswer(200, true, said, null) : redirect(response, chatReturnWithLatest(back));
754
+ }
755
+ }
703
756
  if (cardJson) {
704
757
  if (!outcome.ok)
705
758
  return cardAnswer(outcome.reason === "standing" ? 403 : outcome.reason === "not-yours" ? 404 : 409, false, outcome.said);
@@ -791,10 +844,12 @@ export function createChatHandlers(runtime) {
791
844
  const enabled = chatEnablement();
792
845
  if (!enabled.ok)
793
846
  return said(409, enabled.why);
794
- let leadSession = who.role === "approver" ? store.activeLeadSession(who.name) : null;
847
+ let leadSession = who.role === "approver" ? store.activeLeadSession(who.name, enabled.credentialKey) : null;
795
848
  let startedHere = false;
796
849
  const binding = body.getAll("request-session");
797
850
  const unbound = binding.length === 0 || (binding.length === 1 && binding[0] === String(NOT_STARTED_SESSION));
851
+ if (!unbound && leadSession === null && store.activeLeadSession(who.name) !== null)
852
+ return said(409, "The Lead conversation changed. Reload and send your message again.");
798
853
  if (who.role === "approver" && enabled.billing === "subscription" && unbound) {
799
854
  const principal = leadPrincipal(who);
800
855
  if (principal === null)
@@ -821,7 +876,7 @@ export function createChatHandlers(runtime) {
821
876
  return said(400, "that looks like a credential — chat never forwards or stores those");
822
877
  const scope = chatScopeOf(focusTask, chatProject);
823
878
  const started = startLeadConversation(who, principal, enabled, 0, false, now, scope, sentRequest ?? undefined);
824
- leadSession = store.activeLeadSession(who.name);
879
+ leadSession = store.activeLeadSession(who.name, enabled.credentialKey);
825
880
  if (leadSession === null || leadSession.id !== started)
826
881
  return said(409, "This conversation changed. Reload it before sending your message.");
827
882
  startedHere = true;
@@ -863,22 +918,43 @@ export function createChatHandlers(runtime) {
863
918
  const liveShape = { asked: message, appOrigin: requestContext.getStore()?.appOrigins ?? null };
864
919
  const ended = (ok) => { if (onProgress !== undefined)
865
920
  endLiveTurn(opened.thread.id, ok, onProgress); };
921
+ const { promise: admission, resolve: finishAdmission } = deferredAdmission();
922
+ const canActLocally = viewAllowed(request, who);
923
+ const wantsInstantLocal = canActLocally && body.get("instant") === "1";
924
+ const userImages = parseLeadImagesField(body.get("images"));
866
925
  void freshFacts.run(null, () => runLeadTurn({ store, who: principal, session: leadSession, thread: opened.thread, config: enabled.config, key: enabled.key, message,
867
- onAdmitted: () => { onProgress = beginLiveTurn(opened.thread.id, liveShape); }, onProgress: event => onProgress?.(event), channel: "console", requestId,
868
- ...(viewAllowed(request, who) ? { view: viewRunner } : {}), ...(focusTask === null && chatProject !== null ? { context: `Current project: ${projectName(chatProject)} (${chatProject}). Keep this conversation about that project unless the operator explicitly asks to broaden it; use it as the repo for project tools.` } : {}), ...(focusTask === null ? {} : { context: `Current task: ${focusTask.id}. Read it with get_task before answering or proposing changes. Read its currentExecution next and bind new actions to that exact execution. Never replace the target of a prior proposal with a newer revision. Keep this turn about that task unless the operator explicitly asks to broaden it.${resultContext}${modeContext}` }), fetcher: chatFetcher, ...(options.subscriptionChatRunner === undefined ? {} : { subscriptionRunner: options.subscriptionChatRunner }), clock, evidenceRoot }))
926
+ ...(userImages.length > 0 ? { images: userImages } : {}),
927
+ onAdmitted: () => { onProgress = beginLiveTurn(opened.thread.id, liveShape); finishAdmission({ queued: false }); }, onProgress: event => onProgress?.(event), channel: "console", requestId,
928
+ ...(canActLocally ? {
929
+ view: viewRunner,
930
+ ...(wantsInstantLocal ? { instantLocal: { authority: who.authority, evidenceRoot, chatProvider: teamChatProvider } } : {}),
931
+ ...(extras?.directChatStop === undefined ? {} : { directChatStop: extras.directChatStop }),
932
+ ...(extras?.directChatDiff === undefined ? {} : { directChatDiff: extras.directChatDiff }),
933
+ ...(extras?.publishDirectChat === undefined ? {} : { publishDirectChat: extras.publishDirectChat }),
934
+ } : {}), ...(focusTask === null && chatProject !== null ? { context: `Current project: ${projectName(chatProject)} (${chatProject}). Keep this conversation about that project unless the operator explicitly asks to broaden it; use it as the repo for project tools.` } : {}), ...(focusTask === null ? {} : { context: `Current task: ${focusTask.id}. Read it with get_task before answering or proposing changes. Read its currentExecution next and bind new actions to that exact execution. Never replace the target of a prior proposal with a newer revision. Keep this turn about that task unless the operator explicitly asks to broaden it.${resultContext}${modeContext}` }), fetcher: chatFetcher, ...(options.subscriptionChatRunner === undefined ? {} : { subscriptionRunner: options.subscriptionChatRunner }), clock, evidenceRoot }))
869
935
  .then(outcome => {
870
936
  if (!outcome.ok && "refused" in outcome && (outcome.refused === "concurrent" || outcome.refused === "backlog") && queueIt().kind === "queued") {
937
+ finishAdmission({ queued: true });
871
938
  ended(false);
872
939
  return;
873
940
  }
874
941
  if (!outcome.ok && !("saved" in outcome && outcome.saved === true) && !("turn" in outcome))
875
942
  noteLead(who.session.csrf, null, outcome.message);
943
+ finishAdmission(outcome.ok ? { queued: false } : { refused: outcome.message });
876
944
  ended(outcome.ok);
877
945
  })
878
- .catch(() => { noteLead(who.session.csrf, null, "the turn failed unexpectedly"); ended(false); })
946
+ .catch(() => { finishAdmission({ refused: "Lead could not start this message. Try again." }); noteLead(who.session.csrf, null, "the turn failed unexpectedly"); ended(false); })
879
947
  .finally(() => runtime.personalQueue.kick());
880
- if (wantsJson)
881
- return respond(response, 202, "application/json", JSON.stringify({ ok: true, session: leadSession.id, task: focusTask?.id ?? "", ...(chatProject === null ? {} : { project: chatProject }), request: requestId }));
948
+ if (wantsJson) {
949
+ const terminal = request.headers["x-toolroll-client"] === "terminal";
950
+ const result = terminal ? await admission : { queued: false };
951
+ if ("refused" in result)
952
+ return said(409, result.refused, leadSession.id);
953
+ if (terminal && !store.leadRequestReceived(leadSession.id, requestId))
954
+ return said(409, "Lead did not receive the message. Send it again.", leadSession.id);
955
+ return respond(response, 202, "application/json", JSON.stringify({ ok: true, ...(result.queued ? { queued: true } : {}),
956
+ session: leadSession.id, task: focusTask?.id ?? "", ...(chatProject === null ? {} : { project: chatProject }), request: requestId }));
957
+ }
882
958
  return redirect(response, chatReturnWithLatest(back));
883
959
  }
884
960
  if (wantsJson)
@@ -1392,3 +1468,8 @@ export function createChatHandlers(runtime) {
1392
1468
  fromThisComputer: runtime.fromThisComputer(request), approvers: store.listApprovers().map(one => one.name) });
1393
1469
  return { registrations, chatFirstRun, phoneCard, chatProjectOf, beginLiveTurn, endLiveTurn, noteLead, takeLeadNote, demoResultView, storeChatKey, forgetChatKey, sweepChatDrafts, runChatTurn, chatHomeOf, firstTasksFor, approverCandidateCount, evictOldestCandidate };
1394
1470
  }
1471
+ function deferredAdmission() {
1472
+ let resolve;
1473
+ const promise = new Promise(done => { resolve = done; });
1474
+ return { promise, resolve };
1475
+ }