toolroll 0.9.109 → 0.9.110

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 (135) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/agent-detect.js +244 -0
  3. package/dist/agent-fence.js +12 -1
  4. package/dist/agentconfig.js +2 -2
  5. package/dist/approval-summary.js +344 -0
  6. package/dist/attest.js +2 -2
  7. package/dist/browser/workspace.css +2 -2
  8. package/dist/browser/workspace.js +27 -27
  9. package/dist/builder.js +36 -2
  10. package/dist/chat-actions.js +24 -17
  11. package/dist/chat-core.js +3 -1
  12. package/dist/chat-decide.js +101 -46
  13. package/dist/chat-delivery-state.js +2 -0
  14. package/dist/chat-delivery.js +3 -2
  15. package/dist/chat-live.js +2 -1
  16. package/dist/chat-task-actions.js +6 -0
  17. package/dist/check-report.js +1 -1
  18. package/dist/cli.js +2 -0
  19. package/dist/console-instance.js +10 -1
  20. package/dist/contracts/console-api.js +10 -5
  21. package/dist/contracts/engine-api.js +271 -0
  22. package/dist/coordinator.js +2 -2
  23. package/dist/discord-api.js +4 -3
  24. package/dist/discord-chat.js +3 -1
  25. package/dist/easy-start-args.js +7 -3
  26. package/dist/easy-start.js +25 -0
  27. package/dist/egress.js +72 -10
  28. package/dist/engine-handoff.js +34 -0
  29. package/dist/engine-reads.js +261 -0
  30. package/dist/eval-world.js +3 -2
  31. package/dist/evidence.js +2 -0
  32. package/dist/fast-start.js +55 -14
  33. package/dist/fast-terms.js +2 -2
  34. package/dist/first-run.js +10 -2
  35. package/dist/flexible-agents.js +234 -0
  36. package/dist/flexible-answers-schema.js +61 -0
  37. package/dist/flexible-answers.js +889 -0
  38. package/dist/flexible-custody.js +494 -0
  39. package/dist/flexible-import.js +782 -0
  40. package/dist/flexible-launch-schema.js +72 -0
  41. package/dist/flexible-launch.js +331 -0
  42. package/dist/flexible-launcher.js +88 -0
  43. package/dist/flexible-levels.js +34 -0
  44. package/dist/flexible-merge-guard.js +47 -0
  45. package/dist/flexible-refs.js +47 -0
  46. package/dist/flexible-relay-cancel.js +19 -0
  47. package/dist/flexible-relay-schema.js +55 -0
  48. package/dist/flexible-relay-upstreams.js +36 -0
  49. package/dist/flexible-relay.js +1032 -0
  50. package/dist/flexible-session.js +732 -0
  51. package/dist/flexible-ship-schema.js +81 -0
  52. package/dist/flexible-ship.js +694 -0
  53. package/dist/flexible-start.js +80 -0
  54. package/dist/flexible-thread.js +175 -25
  55. package/dist/flexible-turns-schema.js +69 -0
  56. package/dist/flexible-turns.js +490 -0
  57. package/dist/flexible.js +10 -1
  58. package/dist/flow-actions.js +6 -4
  59. package/dist/flow-steps.js +1 -1
  60. package/dist/flows-cli.js +2 -1
  61. package/dist/git-views.js +6 -3
  62. package/dist/install-mode.js +225 -0
  63. package/dist/lead-doors.js +7 -1
  64. package/dist/limits-ui.js +7 -0
  65. package/dist/live-reply.js +6 -0
  66. package/dist/live-terminal.js +425 -29
  67. package/dist/local-owner.js +6 -0
  68. package/dist/model-choices.js +12 -6
  69. package/dist/notification-delivery.js +11 -0
  70. package/dist/operate.js +74 -30
  71. package/dist/outbound-privacy.js +204 -0
  72. package/dist/passwordless.js +2 -1
  73. package/dist/project-delete.js +14 -0
  74. package/dist/provider-connection.js +5 -3
  75. package/dist/publish.js +5 -0
  76. package/dist/pull-request-flow.js +26 -7
  77. package/dist/push.js +5 -1
  78. package/dist/release-card.js +11 -3
  79. package/dist/release.js +10 -1
  80. package/dist/route-store.js +2 -2
  81. package/dist/sandbox-launch.js +32 -8
  82. package/dist/sandbox-runtime.js +16 -7
  83. package/dist/sandbox-tools.js +176 -0
  84. package/dist/scope.js +12 -36
  85. package/dist/scout-net.js +7 -2
  86. package/dist/serve.js +58 -11
  87. package/dist/server/chrome.js +3 -1
  88. package/dist/server/console.css +33 -6
  89. package/dist/server/engine-api.js +378 -0
  90. package/dist/server/flows.js +2 -2
  91. package/dist/server/http.js +7 -0
  92. package/dist/server/link-redemption.js +52 -0
  93. package/dist/server/mutation-key.js +21 -7
  94. package/dist/server/pages.js +69 -40
  95. package/dist/server/people-tokens.js +17 -41
  96. package/dist/server/render-chat.js +1 -0
  97. package/dist/server/render-new-task.js +3 -3
  98. package/dist/server/render-results.js +4 -4
  99. package/dist/server/render-tasks.js +129 -138
  100. package/dist/server/route-table.js +30 -1
  101. package/dist/server/settings-section-table.js +3 -0
  102. package/dist/server/settings-sections.js +33 -0
  103. package/dist/server/settings.js +84 -10
  104. package/dist/server/task-views.js +8 -2
  105. package/dist/server/tasks.js +25 -8
  106. package/dist/server/terminals.js +181 -28
  107. package/dist/server/welcome.js +35 -10
  108. package/dist/settings-groups-ui.js +2 -2
  109. package/dist/settings-proofs.js +13 -9
  110. package/dist/slack-api.js +4 -3
  111. package/dist/slack-chat.js +5 -3
  112. package/dist/spend.js +46 -12
  113. package/dist/status-probe.js +343 -0
  114. package/dist/store.js +102 -5
  115. package/dist/teams-api.js +4 -3
  116. package/dist/teams-chat.js +4 -2
  117. package/dist/telegram-lead.js +2 -1
  118. package/dist/telegram-live.js +2 -1
  119. package/dist/telegram-team.js +2 -1
  120. package/dist/telegram.js +17 -5
  121. package/dist/trusted-path.js +162 -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-launch.js +282 -0
  127. package/dist/tui-source.js +5 -3
  128. package/dist/tui.js +1 -1
  129. package/dist/webhooks.js +8 -4
  130. package/dist/welcome-facts.js +22 -15
  131. package/dist/workspace-ui.js +5 -0
  132. package/package.json +1 -1
  133. package/scripts/crash-canary.mjs +1 -1
  134. package/scripts/pilot.mjs +1 -1
  135. package/scripts/provider-canary.mjs +5 -3
package/dist/teams-api.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { chmodSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { guardTeams } from "./outbound-privacy.js";
3
4
  import { createPublicKey, randomBytes, verify as verifySignature } from "node:crypto";
4
- import { ChatDeliveryError, chatHash } from "./chat-delivery-state.js";
5
+ import { ChatDeliveryError, chatHash, withheldPart } from "./chat-delivery-state.js";
5
6
  import { chatObject as object } from "./chat-delivery.js";
6
7
  export class TeamsError extends ChatDeliveryError {
7
8
  }
@@ -68,7 +69,7 @@ export async function teamsAccessToken(credentials, fetcher = fetch, now = Date.
68
69
  }
69
70
  export function forgetTeamsToken() { cachedToken = null; }
70
71
  export function teamsApi(credentials, fetcher = fetch) {
71
- return async (method, serviceUrl, path, body) => {
72
+ return guardTeams(async (method, serviceUrl, path, body) => {
72
73
  if (!/^\/v3\/conversations\/[A-Za-z0-9:@._%-]+(?:\/activities(?:\/[A-Za-z0-9:._%-]+)?|\/members(?:\/[A-Za-z0-9:._%-]+)?)$/.test(path))
73
74
  throw new TeamsError("Invalid Teams request");
74
75
  let base;
@@ -111,7 +112,7 @@ export function teamsApi(credentials, fetcher = fetch) {
111
112
  catch {
112
113
  return {};
113
114
  }
114
- };
115
+ }, withheldPart);
115
116
  }
116
117
  export async function checkTeamsCredentials(app, tenant, secret, fetcher = fetch) {
117
118
  if (!teamsGuid(app) || !teamsGuid(tenant))
@@ -1,7 +1,7 @@
1
1
  import { resultShotsPruned } from "./result-shots.js";
2
2
  import { chatQuestionButtons } from "./subagent-question.js";
3
3
  import { chatAskButtons } from "./chat-ask.js";
4
- import { ChatDeliveryError, ChatState, chatHash, chatRetryAt, partContent } from "./chat-delivery-state.js";
4
+ import { ChatDeliveryError, ChatState, chatHash, chatRetryAt, partContent, withheldPart } from "./chat-delivery-state.js";
5
5
  import { isLiveMessage, liveSpacingOf, underCooldown } from "./chat-live.js";
6
6
  import { channelAccess, chatObject as object, heldForWatch, planChatNotifications, planRoomMessages, processChatEvent, splitChatText } from "./chat-delivery.js";
7
7
  import { PLATFORM_LIMITS } from "./text-limits.js";
@@ -14,6 +14,7 @@ import { chatResultHref } from "./chat-controls.js";
14
14
  import { TeamsError } from "./teams-api.js";
15
15
  import { readTeamsSubmit } from "./contracts/teams-callback.js";
16
16
  import { readChatPart } from "./contracts/chat-content.js";
17
+ import { checkedChunks, guardTeams, taskSubject } from "./outbound-privacy.js";
17
18
  const TEAMS_GONE = "Teams refused the request (404)";
18
19
  const TEAMS_SLOW = "Teams asked to slow down";
19
20
  const serviceKey = (conversation) => `serviceUrl:${conversation}`;
@@ -141,7 +142,7 @@ export function teamsCard(text, actions) {
141
142
  };
142
143
  }
143
144
  export function teamsMessages(text, markdown, last) {
144
- const parts = text.length <= PLATFORM_LIMITS.teams ? [text] : splitChatText(text, PLATFORM_LIMITS.teams);
145
+ const parts = checkedChunks(text, text.length <= PLATFORM_LIMITS.teams ? [text] : splitChatText(text, PLATFORM_LIMITS.teams));
145
146
  return parts.map((part, at) => at === parts.length - 1 ? last(part) : { type: "message", text: part, textFormat: markdown ? "markdown" : "plain" });
146
147
  }
147
148
  export async function deliverTeamsPart(options) {
@@ -162,6 +163,7 @@ export async function deliverTeamsPart(options) {
162
163
  if (event.kind === "notice" && options.canNotify?.() === false)
163
164
  return false;
164
165
  const content = partContent(row.payload);
166
+ options = { ...options, api: guardTeams(options.api, withheldPart, taskSubject(store, content.task ?? content.image?.taskId)) };
165
167
  const destination = content.channel ?? binding.channel;
166
168
  const serviceUrl = state.meta(identity.installation, serviceKey(destination));
167
169
  if (serviceUrl === null)
@@ -11,6 +11,7 @@ import { ceilingDigestOf, verifyApproverStanding } from "./principal.js";
11
11
  import { CONFIRM_TTL_MS, LEAD_ASK_OTHER } from "./store.js";
12
12
  import { phoneText } from "./telegram-status.js";
13
13
  import { shapeReplyParts, telegramReply } from "./reply-shape.js";
14
+ import { checkedChunks } from "./outbound-privacy.js";
14
15
  import { createTelegramLiveDraft, forgetWaitingDraft, telegramAck, telegramWaitingDraft } from "./telegram-live.js";
15
16
  import { TeamLeads } from "./team-leads.js";
16
17
  import { chatResultHref } from "./chat-controls.js";
@@ -497,7 +498,7 @@ async function runTelegramConversation(row, args) {
497
498
  try {
498
499
  return store.transact(() => {
499
500
  const now = clock();
500
- const parts = shapeReplyParts(reply, PART_CAP, { asked: row.text, appOrigin: options.phoneOrigin?.() ?? null }, shaped => telegramReply(shaped).text.length).map((text, index) => ({ kind: "reply", text, replyTo: index === 0 ? row.messageId : null }));
501
+ const parts = checkedChunks(reply, shapeReplyParts(reply, PART_CAP, { asked: row.text, appOrigin: options.phoneOrigin?.() ?? null }, shaped => telegramReply(shaped).text.length)).map((text, index) => ({ kind: "reply", text, replyTo: index === 0 ? row.messageId : null }));
501
502
  const ask = store.leadAsk(turn);
502
503
  if (ask !== null)
503
504
  parts.push({ kind: "reply", text: phoneText(ask.question, 1_000), keyboard: askKeyboard(ask) });
@@ -1,4 +1,5 @@
1
1
  import { createLiveReply, createLiveSender, LIVE_STATUS } from "./live-reply.js";
2
+ import { privateValue, safeWords } from "./outbound-privacy.js";
2
3
  import { shapedWindow, telegramReply } from "./reply-shape.js";
3
4
  export const ACK_EMOJI = "👀";
4
5
  export const ACK_GAP_MS = 1_000;
@@ -34,7 +35,7 @@ export function telegramDraftOf(view) {
34
35
  }
35
36
  const head = view.status;
36
37
  const gap = "\n\n";
37
- const body = draftBody(view.text, TELEGRAM_TEXT_MAX - head.length - gap.length);
38
+ const body = privateValue(view.text) ? { text: safeWords(null), entities: [] } : draftBody(view.text, TELEGRAM_TEXT_MAX - head.length - gap.length);
38
39
  if (body.text === "")
39
40
  return { text: head, entities: [{ type: "italic", offset: 0, length: head.length }] };
40
41
  const shift = head.length + gap.length;
@@ -1,4 +1,5 @@
1
1
  import { renderReply, shapeReplyParts } from "./reply-shape.js";
2
+ import { checkedChunks } from "./outbound-privacy.js";
2
3
  import { TeamLeads } from "./team-leads.js";
3
4
  import { proposalPreview, tooLongText } from "./chat-channel.js";
4
5
  import { PART_CAP, mintCardTokens, phoneLinkButton, splitParts } from "./telegram-lead.js";
@@ -239,7 +240,7 @@ export async function deliverTeamChats(store, botId, transport, clock, report, p
239
240
  const skip = role === "operator" && (ownMessage || status === "cancelled" || String(message["author"] ?? "").length === 0);
240
241
  const prefix = `telegram-team:${chat.id}:`;
241
242
  if (!skip) {
242
- const text = role === "assistant" ? shapeReplyParts(String(message["text"]), PART_CAP, { appOrigin: phoneOrigin?.() ?? null }, shaped => renderReply(shaped, "telegram").length).map(part => renderReply(part, "telegram")) : `${phoneText(String(message["author"]), 40)}: ${String(message["text"])}`;
243
+ const text = role === "assistant" ? checkedChunks(String(message["text"]), shapeReplyParts(String(message["text"]), PART_CAP, { appOrigin: phoneOrigin?.() ?? null }, shaped => renderReply(shaped, "telegram").length)).map(part => renderReply(part, "telegram")) : `${phoneText(String(message["author"]), 40)}: ${String(message["text"])}`;
243
244
  const sent = await sendParts(store, transport, chat.chatId, text, `${prefix}message:${id}`, clock, access, report);
244
245
  if (sent !== null) {
245
246
  report.problems.push(`team chat ${chat.chatId}: ${sent}`);
package/dist/telegram.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { recordTypedStart, typedStartCard, typedYes } from "./typed-start.js";
2
2
  import { telegramCardMessage } from "./card-render.js";
3
3
  import { flowDoneCard } from "./flow-result-card.js";
4
+ import { guardTelegram, outboundPrivate, privateValue, safeWords, taskSubject } from "./outbound-privacy.js";
4
5
  import { applyTelegramQuestionReply, applyTelegramQuestionTap, openQuestionOf, telegramQuestionButtons } from "./subagent-question.js";
5
6
  import { acceptanceEvidenceText } from "./chat-acceptance.js";
6
7
  import { verifyApproverStanding } from "./principal.js";
@@ -134,8 +135,8 @@ export function scrub(text, token) {
134
135
  return token === "" ? text : text.split(token).join(redactToken(token));
135
136
  }
136
137
  export const termsUpload = (file) => ({ field: "document", fileName: file.name, contentType: "text/plain", bytes: Buffer.from(file.text, "utf8") });
137
- export function createTransport(token, timeoutMs = 30_000) {
138
- return async (method, params, signal, upload, more) => {
138
+ export function createTransport(token, timeoutMs = 30_000, fetcher) {
139
+ return guardTelegram(async (method, params, signal, upload, more) => {
139
140
  const controller = new AbortController();
140
141
  const timer = setTimeout(() => controller.abort(), timeoutMs);
141
142
  const onAbort = () => controller.abort();
@@ -149,7 +150,7 @@ export function createTransport(token, timeoutMs = 30_000) {
149
150
  const request = upload === undefined
150
151
  ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(params), signal: controller.signal }
151
152
  : { method: "POST", body: multipartOf(params, upload, ...(more ?? [])), signal: controller.signal };
152
- const response = await fetch(`https://api.telegram.org/bot${token}/${method}`, request);
153
+ const response = await (fetcher ?? fetch)(`https://api.telegram.org/bot${token}/${method}`, request);
153
154
  const body = (await response.json());
154
155
  if (body === null || typeof body !== "object" || Array.isArray(body) || typeof body.ok !== "boolean" || (body.ok && !response.ok)) {
155
156
  return { ok: false, description: "Telegram returned an invalid acknowledgement", uncertain: true };
@@ -172,7 +173,7 @@ export function createTransport(token, timeoutMs = 30_000) {
172
173
  clearTimeout(timer);
173
174
  signal?.removeEventListener("abort", onAbort);
174
175
  }
175
- };
176
+ });
176
177
  }
177
178
  export function networkFence(env) {
178
179
  const set = (name) => (env[name] ?? "") !== "";
@@ -649,8 +650,11 @@ async function deliverOutboxTo(store, botId, binding, transport, owner, clock, r
649
650
  continue;
650
651
  const ids = rows.map(row => row.id);
651
652
  let sentAny = false;
653
+ const subject = { project: new Set(rows.map(row => row.project)).size === 1 ? rows[0].project : null,
654
+ withheld: rows.some(row => outboundPrivate([row.subject, row.body]) || taskSubject(store, row.taskId).withheld === true) };
655
+ const guarded = guardTelegram(transport, subject);
652
656
  const wire = async (...args) => {
653
- const answer = await transport(...args);
657
+ const answer = await guarded(...args);
654
658
  if (answer.ok === true)
655
659
  sentAny = true;
656
660
  return answer;
@@ -1025,6 +1029,10 @@ function digestEntry(row, titleOf) {
1025
1029
  }
1026
1030
  async function deliverDigest(botId, binding, sender, rows, since, clock, titleOf) {
1027
1031
  const text = digestText(rows, since, clock(), titleOf);
1032
+ if (privateValue(text)) {
1033
+ const sent = await sender(safeWords({ project: new Set(rows.map(row => row.project)).size === 1 ? rows[0].project : null }), undefined, rows);
1034
+ return sent.ok ? { ok: true, receipt: receiptFor(botId, binding.chatId, sent.messageId) } : sent;
1035
+ }
1028
1036
  let offset = text.indexOf("\n\n") + 2;
1029
1037
  const spans = rows.map(row => {
1030
1038
  const length = digestEntry(row, titleOf).length;
@@ -2068,6 +2076,10 @@ function applyCallback(context, update, effects) {
2068
2076
  dropDecideTokens(store, tapped.edit.tokens, clock());
2069
2077
  editText(`${message.text ?? ""}\n\nThis release can't be approved here. Open it in Toolroll.`.trim().slice(0, 4000), []);
2070
2078
  }
2079
+ else if (tapped.edit !== undefined && tapped.edit.text.length > 4000 && tapped.edit.tokens.length > 0) {
2080
+ dropDecideTokens(store, tapped.edit.tokens, clock());
2081
+ editText(`${tapped.edit.text.slice(0, 3_000)}…\n\nThis doesn't fit in one Telegram message, so you approve it in Toolroll. Nothing was done.`, []);
2082
+ }
2071
2083
  else if (tapped.edit !== undefined)
2072
2084
  editText(tapped.edit.text.slice(0, 4000), decideKeyboard(context.conversation?.phoneOrigin, tapped.edit.rows));
2073
2085
  if (tapped.prompt !== undefined) {
@@ -0,0 +1,162 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import { dirname, isAbsolute } from "node:path";
4
+ const ACL_CHANGE = new Set(["write", "append", "add_file", "add_subdirectory", "delete", "delete_child", "writeattr", "writeextattr", "writesecurity", "chown"]);
5
+ const ACL_RIGHTS = new Set([...ACL_CHANGE, "read", "execute", "readattr", "readextattr", "readsecurity", "list", "search", "file_inherit", "directory_inherit", "limit_inherit", "only_inherit"]);
6
+ const ACL_READ_MS = 3_000;
7
+ export const platformAcl = () => (process.platform === "darwin" ? macAcl : null);
8
+ export function boundedAcl(deadline, read = process.platform === "darwin" ? macAclWithin : null) {
9
+ if (read === null)
10
+ return null;
11
+ const seen = new Map();
12
+ return path => {
13
+ let verdict = seen.get(path);
14
+ if (verdict === undefined) {
15
+ const left = deadline - Date.now();
16
+ verdict = left <= 0 ? { ok: false, why: "can't be read in time" } : read(path, Math.min(left, ACL_READ_MS));
17
+ seen.set(path, verdict);
18
+ }
19
+ return verdict;
20
+ };
21
+ }
22
+ export function trustedFolders(folder, uid, acl) {
23
+ const owned = (owner) => owner === uid || owner === 0;
24
+ try {
25
+ for (let first = true;; first = false) {
26
+ const dir = lstatSync(folder);
27
+ if (!dir.isDirectory())
28
+ return { ok: false, why: `${folder} isn't a folder` };
29
+ if (!owned(dir.uid))
30
+ return { ok: false, why: `${folder} is owned by another user` };
31
+ const sticky = (dir.mode & 0o1000) !== 0;
32
+ if ((dir.mode & 0o022) !== 0 && (first || !sticky))
33
+ return { ok: false, why: `others can change ${folder} (group- or world-writable)` };
34
+ const dirAcl = acl?.(folder);
35
+ if (dirAcl !== undefined && !dirAcl.ok)
36
+ return { ok: false, why: `the ACL of ${folder} ${dirAcl.why}` };
37
+ const up = dirname(folder);
38
+ if (up === folder)
39
+ return { ok: true };
40
+ folder = up;
41
+ }
42
+ }
43
+ catch (error) {
44
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
45
+ }
46
+ }
47
+ export function trustedBinary(path, uid, acl = platformAcl()) {
48
+ if (!isAbsolute(path))
49
+ return { ok: false, why: "it isn't an absolute path" };
50
+ if (uid === undefined)
51
+ return { ok: false, why: "who owns it can't be checked on this system" };
52
+ let real;
53
+ try {
54
+ real = realpathSync(path);
55
+ }
56
+ catch (error) {
57
+ return { ok: false, why: `it isn't there (${error.code ?? "unreadable"})` };
58
+ }
59
+ try {
60
+ const file = lstatSync(real);
61
+ if (!file.isFile())
62
+ return { ok: false, why: "it isn't a file" };
63
+ if (file.uid !== uid && file.uid !== 0)
64
+ return { ok: false, why: "it is owned by another user" };
65
+ if ((file.mode & 0o022) !== 0)
66
+ return { ok: false, why: "others can change it (group- or world-writable)" };
67
+ const fileAcl = acl?.(real);
68
+ if (fileAcl !== undefined && !fileAcl.ok)
69
+ return { ok: false, why: `its ACL ${fileAcl.why}` };
70
+ }
71
+ catch (error) {
72
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
73
+ }
74
+ const folders = trustedFolders(dirname(real), uid, acl);
75
+ return folders.ok ? { ok: true, real } : folders;
76
+ }
77
+ export function rootOwnedFolders(folder, acl = platformAcl(), owners = [0], who = "root") {
78
+ let real;
79
+ try {
80
+ real = realpathSync(folder);
81
+ }
82
+ catch (error) {
83
+ return { ok: false, why: `${folder} isn't there (${error.code ?? "unreadable"})` };
84
+ }
85
+ try {
86
+ for (let at = real;; at = dirname(at)) {
87
+ const dir = lstatSync(at);
88
+ if (!dir.isDirectory())
89
+ return { ok: false, why: `${at} isn't a folder` };
90
+ if (!owners.includes(dir.uid))
91
+ return { ok: false, why: `${at} isn't owned by ${who}` };
92
+ if ((dir.mode & 0o022) !== 0)
93
+ return { ok: false, why: `others can change ${at} (group- or world-writable)` };
94
+ const dirAcl = acl?.(at);
95
+ if (dirAcl !== undefined && !dirAcl.ok)
96
+ return { ok: false, why: `the ACL of ${at} ${dirAcl.why}` };
97
+ if (dirname(at) === at)
98
+ return { ok: true, real };
99
+ }
100
+ }
101
+ catch (error) {
102
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
103
+ }
104
+ }
105
+ export function rootOwnedBinary(path, acl = platformAcl(), owners = [0], who = "root") {
106
+ if (!isAbsolute(path))
107
+ return { ok: false, why: "it isn't an absolute path" };
108
+ let real;
109
+ try {
110
+ real = realpathSync(path);
111
+ }
112
+ catch (error) {
113
+ return { ok: false, why: `it isn't there (${error.code ?? "unreadable"})` };
114
+ }
115
+ try {
116
+ const file = lstatSync(real);
117
+ if (!file.isFile())
118
+ return { ok: false, why: "it isn't a file" };
119
+ if (!owners.includes(file.uid))
120
+ return { ok: false, why: `${real} isn't owned by ${who}` };
121
+ if ((file.mode & 0o022) !== 0)
122
+ return { ok: false, why: `others can change ${real} (group- or world-writable)` };
123
+ const fileAcl = acl?.(real);
124
+ if (fileAcl !== undefined && !fileAcl.ok)
125
+ return { ok: false, why: `its ACL ${fileAcl.why}` };
126
+ }
127
+ catch (error) {
128
+ return { ok: false, why: `it can't be checked (${error.code ?? "unreadable"})` };
129
+ }
130
+ const folders = rootOwnedFolders(dirname(real), acl, owners, who);
131
+ return folders.ok ? { ok: true, real } : folders;
132
+ }
133
+ export function aclVerdictOf(output) {
134
+ const lines = output.split("\n");
135
+ if (lines.at(-1) === "")
136
+ lines.pop();
137
+ if (lines.length === 0 || !/^[-dlbcpsw][-rwxsStT]{9}[@+]? /.test(lines[0]))
138
+ return { ok: false, why: "can't be read" };
139
+ for (const line of lines.slice(1)) {
140
+ const entry = /^ \d+: (\S.*?) (?:inherited )?(allow|deny) ([a-z_]+(?:,[a-z_]+)*)$/.exec(line);
141
+ if (entry === null)
142
+ return { ok: false, why: "can't be read" };
143
+ const rights = entry[3].split(",");
144
+ if (rights.some(right => !ACL_RIGHTS.has(right)))
145
+ return { ok: false, why: "can't be read (an unknown right)" };
146
+ const granted = rights.filter(right => ACL_CHANGE.has(right));
147
+ if (entry[2] === "allow" && granted.length > 0)
148
+ return { ok: false, why: `allows ${entry[1]} to change it (${granted.join(",")})` };
149
+ }
150
+ return { ok: true };
151
+ }
152
+ function macAcl(path) {
153
+ return macAclWithin(path, ACL_READ_MS);
154
+ }
155
+ function macAclWithin(path, ms) {
156
+ if (/[\u0000-\u001f\u007f]/.test(path))
157
+ return { ok: false, why: "can't be read (a control character in the path)" };
158
+ const ran = spawnSync("/bin/ls", ["-lde", "--", path], { encoding: "utf8", timeout: Math.max(1, Math.floor(ms)), env: { LC_ALL: "C", PATH: "/usr/bin:/bin" }, stdio: ["ignore", "pipe", "ignore"] });
159
+ if (ran.status !== 0 || typeof ran.stdout !== "string")
160
+ return { ok: false, why: "can't be read" };
161
+ return aclVerdictOf(ran.stdout);
162
+ }
Binary file
Binary file
@@ -0,0 +1,282 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { spawnHoldingLink } from "./engine-handoff.js";
6
+ import { trustedBinary } from "./trusted-path.js";
7
+ export { aclVerdictOf, trustedBinary } from "./trusted-path.js";
8
+ export const TUI_EXIT = { leave: 0, stop: 40, keep: 41, classic: 42, unprotected: 43 };
9
+ export const TUI_PACKAGES = Object.freeze({
10
+ "darwin-arm64": "@toolroll/tui-darwin-arm64", "darwin-x64": "@toolroll/tui-darwin-x64",
11
+ "linux-x64": "@toolroll/tui-linux-x64", "linux-arm64": "@toolroll/tui-linux-arm64",
12
+ });
13
+ const ASK_CAP = 1024;
14
+ const SELF_CHECK_MS = 3_000;
15
+ const READY_MS = 5_000;
16
+ const KILL_AFTER_MS = 1_000;
17
+ const READY = "protected";
18
+ export const packageRootOf = (moduleUrl) => {
19
+ const root = join(dirname(fileURLToPath(moduleUrl)), "..");
20
+ try {
21
+ return realpathSync(root);
22
+ }
23
+ catch {
24
+ return root;
25
+ }
26
+ };
27
+ const defaultRoot = () => packageRootOf(import.meta.url);
28
+ export const bundledBinary = (root, key) => join(root, "dist", "tui", key, "toolroll-tui");
29
+ const defaultSelfCheck = (binary) => {
30
+ const ran = spawnSync(binary, ["--version"], { encoding: "utf8", timeout: SELF_CHECK_MS, stdio: ["ignore", "pipe", "ignore"] });
31
+ return { status: ran.status, stdout: ran.stdout ?? "", ...(ran.error === undefined ? {} : { error: ran.error.code ?? ran.error.message }) };
32
+ };
33
+ export function identityOf(path) {
34
+ try {
35
+ const st = lstatSync(path, { bigint: true });
36
+ return { dev: st.dev, ino: st.ino, size: st.size, mtimeNs: st.mtimeNs };
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ const sameIdentity = (a, b) => a !== null && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs;
43
+ function presence(path) {
44
+ try {
45
+ lstatSync(path);
46
+ return { kind: "present" };
47
+ }
48
+ catch (error) {
49
+ const code = error.code;
50
+ return code === "ENOENT" ? { kind: "absent" } : { kind: "refused", why: `${path} can't be checked (${code ?? "unreadable"})` };
51
+ }
52
+ }
53
+ function bundledCandidate(root, key) {
54
+ let realRoot;
55
+ try {
56
+ realRoot = realpathSync(root);
57
+ }
58
+ catch (error) {
59
+ const code = error.code;
60
+ return code === "ENOENT" ? { kind: "absent" } : { kind: "refused", why: `${root} can't be checked (${code ?? "unreadable"})` };
61
+ }
62
+ const parts = ["dist", "tui", key, "toolroll-tui"];
63
+ let at = realRoot;
64
+ for (const [i, part] of parts.entries()) {
65
+ at = join(at, part);
66
+ let st;
67
+ try {
68
+ st = lstatSync(at);
69
+ }
70
+ catch (error) {
71
+ const code = error.code;
72
+ if (code === "ENOENT")
73
+ return { kind: "absent" };
74
+ return { kind: "refused", why: `${at} can't be checked (${code ?? "unreadable"})` };
75
+ }
76
+ if (st.isSymbolicLink())
77
+ return { kind: "refused", why: `${at} is a link: the binary the package ships must be inside it` };
78
+ if (i < parts.length - 1 && !st.isDirectory())
79
+ return { kind: "refused", why: `${at} isn't a folder` };
80
+ }
81
+ let real;
82
+ try {
83
+ real = realpathSync(at);
84
+ }
85
+ catch (error) {
86
+ return { kind: "refused", why: `${at} can't be checked (${error.code ?? "unreadable"})` };
87
+ }
88
+ if (!real.startsWith(`${realRoot}${sep}`))
89
+ return { kind: "refused", why: `${at} isn't inside the package` };
90
+ return { kind: "present", path: at };
91
+ }
92
+ function packageCandidates(root, name) {
93
+ const parts = name.split("/");
94
+ const places = [join(root, "node_modules", ...parts)];
95
+ if (basename(dirname(root)) === "node_modules")
96
+ places.push(join(dirname(root), ...parts));
97
+ return places;
98
+ }
99
+ function packageCandidate(root, name) {
100
+ for (const place of packageCandidates(root, name)) {
101
+ const manifestPath = join(place, "package.json");
102
+ const there = presence(manifestPath);
103
+ if (there.kind === "absent")
104
+ continue;
105
+ if (there.kind === "refused")
106
+ return there;
107
+ let manifest;
108
+ try {
109
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
110
+ }
111
+ catch (error) {
112
+ return { kind: "refused", why: `${manifestPath} can't be read (${error.code ?? "not JSON"})` };
113
+ }
114
+ if (manifest.name === name)
115
+ return { kind: "present", path: join(place, "bin", "toolroll-tui") };
116
+ }
117
+ return { kind: "absent" };
118
+ }
119
+ function checkoutCandidate(root) {
120
+ for (const marker of [join(root, ".git"), join(root, "tui", "Cargo.toml")]) {
121
+ const there = presence(marker);
122
+ if (there.kind !== "present")
123
+ return there;
124
+ }
125
+ const built = join(root, "tui", "target", "release", "toolroll-tui");
126
+ const there = presence(built);
127
+ return there.kind === "present" ? { kind: "present", path: built } : there;
128
+ }
129
+ export function chooseTuiBinary(input) {
130
+ const ignored = (input.env["TOOLROLL_TUI_BINARY"] ?? "") === "" ? undefined
131
+ : "TOOLROLL_TUI_BINARY is ignored: pass --tui-binary <absolute path> to use your own build";
132
+ const note = (choice, more) => {
133
+ const notice = [more, ignored].filter(one => one !== undefined).join(". ");
134
+ return notice === "" ? choice : { ...choice, notice };
135
+ };
136
+ if (input.env["TOOLROLL_SCREEN"] === "classic")
137
+ return note({ ok: false, why: "TOOLROLL_SCREEN=classic asks for it" });
138
+ if (input.screenReader)
139
+ return note({ ok: false, why: "it works with screen readers" });
140
+ const root = input.packageRoot ?? defaultRoot();
141
+ const uid = input.uid ?? process.getuid?.();
142
+ const key = `${input.platform}-${input.arch}`;
143
+ const name = Object.hasOwn(TUI_PACKAGES, key) ? TUI_PACKAGES[key] : undefined;
144
+ let binary;
145
+ let notice;
146
+ if (input.devBinary !== undefined && input.devBinary !== null) {
147
+ if (!isAbsolute(input.devBinary))
148
+ return note({ ok: false, why: "--tui-binary needs an absolute path" });
149
+ const trusted = trustedBinary(input.devBinary, uid);
150
+ if (!trusted.ok)
151
+ return note({ ok: false, why: `--tui-binary ${input.devBinary} can't be trusted: ${trusted.why}` });
152
+ binary = trusted.real;
153
+ notice = `Using your own terminal workbench build at ${binary} (--tui-binary)`;
154
+ }
155
+ else {
156
+ const candidates = [
157
+ () => (name === undefined ? { kind: "absent" } : bundledCandidate(root, key)),
158
+ () => (name === undefined ? { kind: "absent" } : packageCandidate(root, name)),
159
+ () => checkoutCandidate(root),
160
+ ];
161
+ let found = null;
162
+ for (const candidate of candidates) {
163
+ const one = candidate();
164
+ if (one.kind === "absent")
165
+ continue;
166
+ if (one.kind === "refused")
167
+ return note({ ok: false, why: `the terminal workbench can't be trusted: ${one.why}` });
168
+ found = one.path ?? null;
169
+ break;
170
+ }
171
+ if (found === null) {
172
+ if (name === undefined)
173
+ return note({ ok: false, why: `the terminal workbench isn't built for ${input.platform}-${input.arch} yet` });
174
+ return note({ ok: false, why: "the terminal workbench isn't installed on this computer" });
175
+ }
176
+ const trusted = trustedBinary(found, uid);
177
+ if (!trusted.ok)
178
+ return note({ ok: false, why: `the terminal workbench at ${found} can't be trusted: ${trusted.why}` });
179
+ binary = trusted.real;
180
+ }
181
+ const identity = identityOf(binary);
182
+ if (identity === null)
183
+ return note({ ok: false, why: `the terminal workbench at ${binary} can't be checked` }, notice);
184
+ const check = (input.selfCheck ?? defaultSelfCheck)(binary);
185
+ if (check.status === TUI_EXIT.unprotected)
186
+ return note({ ok: false, why: "the terminal workbench couldn't turn off crash dumps on this computer" }, notice);
187
+ if (check.status !== 0)
188
+ return note({ ok: false, why: `the terminal workbench didn't start (${check.error ?? (check.status === null ? "no answer" : `exit ${check.status}`)})` }, notice);
189
+ const said = /^toolroll-tui \S+ contract ([0-9a-f]{64})$/.exec(check.stdout.trim());
190
+ if (said === null || said[1] !== input.contract)
191
+ return note({ ok: false, why: "the terminal workbench is from another Toolroll version" }, notice);
192
+ if (!sameIdentity(identityOf(binary), identity))
193
+ return note({ ok: false, why: "the terminal workbench changed while it was being checked" }, notice);
194
+ return note({ ok: true, binary, identity }, notice);
195
+ }
196
+ export async function runTuiBinary(input) {
197
+ const args = ["--control-fd", "4", ...(input.session.owned() ? ["--owned"] : []), ...(input.project === null ? [] : ["--project", input.project])];
198
+ if (!isAbsolute(input.binary))
199
+ throw new Error("the terminal workbench is started only by its checked, absolute path");
200
+ if (input.identity !== undefined && !sameIdentity(identityOf(input.binary), input.identity))
201
+ return "changed";
202
+ const { child, send } = spawnHoldingLink(input.binary, args, input.link, {
203
+ ...(input.cwd === undefined ? {} : { cwd: input.cwd }), ...(input.env === undefined ? {} : { env: input.env }),
204
+ ...(input.stdio === undefined ? {} : { stdio: input.stdio }), control: true,
205
+ });
206
+ input.started?.(child);
207
+ let sentLink = false;
208
+ let expired = false;
209
+ let killTimer;
210
+ const running = () => child.exitCode === null && child.signalCode === null;
211
+ const readyTimer = setTimeout(() => {
212
+ if (sentLink)
213
+ return;
214
+ expired = true;
215
+ if (!running())
216
+ return;
217
+ child.kill("SIGTERM");
218
+ killTimer = setTimeout(() => { if (running())
219
+ child.kill("SIGKILL"); }, input.killAfterMs ?? KILL_AFTER_MS);
220
+ }, input.readyMs ?? READY_MS);
221
+ const asks = child.stdio[4];
222
+ if (asks !== null && asks !== undefined && "on" in asks) {
223
+ let pending = "";
224
+ asks.on("error", () => { });
225
+ asks.on("data", (chunk) => {
226
+ pending += chunk.toString("utf8");
227
+ if (pending.length > ASK_CAP && !pending.includes("\n")) {
228
+ pending = "\u0000";
229
+ return;
230
+ }
231
+ let at;
232
+ while ((at = pending.indexOf("\n")) >= 0) {
233
+ const line = pending.slice(0, at);
234
+ pending = pending.slice(at + 1);
235
+ if (line.startsWith("\u0000") || line.length > ASK_CAP)
236
+ continue;
237
+ let ask = null;
238
+ try {
239
+ ask = JSON.parse(line);
240
+ }
241
+ catch {
242
+ ask = null;
243
+ }
244
+ if (ask !== null && typeof ask === "object" && ask["ready"] === READY) {
245
+ if (!sentLink && !expired) {
246
+ sentLink = send();
247
+ clearTimeout(readyTimer);
248
+ }
249
+ continue;
250
+ }
251
+ if (ask !== null && typeof ask === "object" && ask["want"] === "browser") {
252
+ void input.session.openBrowser().catch(() => "The browser couldn't be opened.").then(said => {
253
+ if ("write" in asks && !child.killed && child.exitCode === null)
254
+ asks.write(`${JSON.stringify({ said })}\n`);
255
+ });
256
+ }
257
+ }
258
+ });
259
+ }
260
+ const forward = (signal) => () => { if (child.exitCode === null)
261
+ child.kill(signal); };
262
+ const handlers = ["SIGTERM", "SIGHUP"].map(signal => [signal, forward(signal)]);
263
+ for (const [signal, handler] of handlers)
264
+ process.on(signal, handler);
265
+ const code = await new Promise(resolve => {
266
+ child.once("error", () => resolve(-1));
267
+ child.once("exit", (exit, signal) => resolve(signal === null ? exit : null));
268
+ });
269
+ for (const [signal, handler] of handlers)
270
+ process.off(signal, handler);
271
+ clearTimeout(readyTimer);
272
+ clearTimeout(killTimer);
273
+ if (!sentLink)
274
+ return "classic";
275
+ if (code === TUI_EXIT.stop)
276
+ return "stop";
277
+ if (code === TUI_EXIT.keep)
278
+ return "keep";
279
+ if (code === TUI_EXIT.classic || code === TUI_EXIT.unprotected || code === -1)
280
+ return "classic";
281
+ return "leave";
282
+ }