toolroll 0.9.108 → 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 (187) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/advanced-view.js +0 -1
  3. package/dist/agent-detect.js +244 -0
  4. package/dist/agent-fence.js +47 -5
  5. package/dist/agent-state.js +5 -2
  6. package/dist/agentconfig.js +2 -2
  7. package/dist/approval-summary.js +344 -0
  8. package/dist/assignment-ui.js +5 -5
  9. package/dist/assignment.js +5 -2
  10. package/dist/attest.js +2 -2
  11. package/dist/browser/terminal.js +1 -1
  12. package/dist/browser/workspace.css +2 -2
  13. package/dist/browser/workspace.js +37 -34
  14. package/dist/browser-crew.js +4 -4
  15. package/dist/browser-workspace.js +4 -11
  16. package/dist/builder.js +45 -3
  17. package/dist/chat-actions.js +24 -17
  18. package/dist/chat-controls.js +6 -5
  19. package/dist/chat-core.js +3 -1
  20. package/dist/chat-decide.js +102 -47
  21. package/dist/chat-delivery-state.js +2 -0
  22. package/dist/chat-delivery.js +3 -2
  23. package/dist/chat-live.js +2 -1
  24. package/dist/chat-quiet.js +3 -3
  25. package/dist/chat-task-actions.js +6 -0
  26. package/dist/chat-voice.js +2 -2
  27. package/dist/check-report.js +1 -1
  28. package/dist/cli-help.js +12 -13
  29. package/dist/cli.js +6 -3
  30. package/dist/console-chrome.js +10 -3
  31. package/dist/console-instance.js +10 -1
  32. package/dist/contracts/console-api.js +14 -8
  33. package/dist/contracts/engine-api.js +271 -0
  34. package/dist/contracts/handoff.js +4 -0
  35. package/dist/coordinator.js +2 -2
  36. package/dist/decision.js +17 -0
  37. package/dist/demo-chat.js +1 -1
  38. package/dist/demo.js +6 -0
  39. package/dist/design/kit.js +4 -3
  40. package/dist/discord-api.js +4 -3
  41. package/dist/discord-chat.js +3 -1
  42. package/dist/dispatch.js +3 -8
  43. package/dist/easy-start-args.js +7 -3
  44. package/dist/easy-start.js +25 -0
  45. package/dist/egress.js +72 -10
  46. package/dist/engine-handoff.js +34 -0
  47. package/dist/engine-reads.js +261 -0
  48. package/dist/eval-world.js +3 -2
  49. package/dist/evidence.js +2 -0
  50. package/dist/fast-start.js +55 -14
  51. package/dist/fast-terms.js +2 -2
  52. package/dist/first-run.js +10 -2
  53. package/dist/flexible-agents.js +234 -0
  54. package/dist/flexible-answers-schema.js +61 -0
  55. package/dist/flexible-answers.js +889 -0
  56. package/dist/flexible-available.js +1 -0
  57. package/dist/flexible-custody.js +494 -0
  58. package/dist/flexible-import.js +782 -0
  59. package/dist/flexible-launch-schema.js +72 -0
  60. package/dist/flexible-launch.js +331 -0
  61. package/dist/flexible-launcher.js +88 -0
  62. package/dist/flexible-levels.js +34 -0
  63. package/dist/flexible-merge-guard.js +47 -0
  64. package/dist/flexible-refs.js +47 -0
  65. package/dist/flexible-relay-cancel.js +19 -0
  66. package/dist/flexible-relay-schema.js +55 -0
  67. package/dist/flexible-relay-upstreams.js +36 -0
  68. package/dist/flexible-relay.js +1032 -0
  69. package/dist/flexible-schema.js +32 -0
  70. package/dist/flexible-session.js +732 -0
  71. package/dist/flexible-ship-schema.js +81 -0
  72. package/dist/flexible-ship.js +694 -0
  73. package/dist/flexible-start.js +80 -0
  74. package/dist/flexible-thread-schema.js +30 -0
  75. package/dist/flexible-thread.js +676 -0
  76. package/dist/flexible-turns-schema.js +69 -0
  77. package/dist/flexible-turns.js +490 -0
  78. package/dist/flexible-ui.js +44 -0
  79. package/dist/flexible.js +368 -0
  80. package/dist/flow-actions.js +6 -4
  81. package/dist/flow-steps.js +1 -1
  82. package/dist/flows-cli.js +2 -1
  83. package/dist/git-views.js +44 -41
  84. package/dist/guides.js +11 -10
  85. package/dist/install-mode.js +225 -0
  86. package/dist/keymap.js +1 -1
  87. package/dist/lead-context.js +1 -1
  88. package/dist/lead-doors.js +7 -1
  89. package/dist/limits-ui.js +8 -1
  90. package/dist/live-bus.js +70 -13
  91. package/dist/live-reply.js +6 -0
  92. package/dist/live-terminal.js +425 -29
  93. package/dist/local-owner.js +6 -0
  94. package/dist/model-choices.js +12 -6
  95. package/dist/needs-you.js +3 -3
  96. package/dist/nightly-github.js +2 -2
  97. package/dist/notification-delivery.js +11 -0
  98. package/dist/operate.js +185 -33
  99. package/dist/outbound-privacy.js +204 -0
  100. package/dist/passwordless.js +2 -1
  101. package/dist/project-delete-ui.js +2 -1
  102. package/dist/project-delete.js +15 -0
  103. package/dist/provider-auth.js +1 -1
  104. package/dist/provider-connection.js +5 -3
  105. package/dist/publish.js +5 -0
  106. package/dist/pull-request-flow.js +26 -7
  107. package/dist/push.js +5 -1
  108. package/dist/release-card.js +11 -3
  109. package/dist/release.js +11 -1
  110. package/dist/result-actions.js +3 -0
  111. package/dist/result-evidence-readers.js +8 -2
  112. package/dist/result-review.js +20 -9
  113. package/dist/route-store.js +2 -2
  114. package/dist/sandbox-launch.js +32 -8
  115. package/dist/sandbox-runtime.js +16 -7
  116. package/dist/sandbox-tools.js +176 -0
  117. package/dist/scope.js +12 -36
  118. package/dist/scout-net.js +7 -2
  119. package/dist/serve.js +90 -40
  120. package/dist/server/chat.js +9 -9
  121. package/dist/server/chrome.js +19 -17
  122. package/dist/server/console.css +33 -6
  123. package/dist/server/engine-api.js +378 -0
  124. package/dist/server/flows.js +2 -2
  125. package/dist/server/guards.js +10 -4
  126. package/dist/server/home.js +37 -5
  127. package/dist/server/http.js +11 -2
  128. package/dist/server/in-place.js +5 -4
  129. package/dist/server/kit.js +2 -2
  130. package/dist/server/link-redemption.js +52 -0
  131. package/dist/server/live.js +100 -10
  132. package/dist/server/mutation-key.js +21 -7
  133. package/dist/server/pages.js +129 -74
  134. package/dist/server/people-tokens.js +17 -41
  135. package/dist/server/render-chat.js +2 -1
  136. package/dist/server/render-history.js +18 -4
  137. package/dist/server/render-new-task.js +4 -4
  138. package/dist/server/render-pages.js +21 -39
  139. package/dist/server/render-people.js +2 -2
  140. package/dist/server/render-projects.js +5 -5
  141. package/dist/server/render-results.js +30 -14
  142. package/dist/server/render-tasks.js +155 -155
  143. package/dist/server/retired-routes.js +37 -4
  144. package/dist/server/route-policy.js +8 -0
  145. package/dist/server/route-table.js +43 -5
  146. package/dist/server/settings-computers.js +140 -0
  147. package/dist/server/settings-scripts.js +15 -0
  148. package/dist/server/settings-section-table.js +59 -0
  149. package/dist/server/settings-sections.js +291 -0
  150. package/dist/server/settings.js +247 -28
  151. package/dist/server/task-views.js +55 -15
  152. package/dist/server/tasks.js +168 -98
  153. package/dist/server/terminals.js +181 -28
  154. package/dist/server/welcome.js +40 -14
  155. package/dist/settings-groups-ui.js +26 -107
  156. package/dist/settings-proofs.js +18 -11
  157. package/dist/slack-api.js +4 -3
  158. package/dist/slack-chat.js +5 -3
  159. package/dist/spend.js +46 -12
  160. package/dist/sqlite-telemetry.js +70 -21
  161. package/dist/status-probe.js +343 -0
  162. package/dist/store.js +206 -10
  163. package/dist/task-link.js +64 -0
  164. package/dist/teams-api.js +4 -3
  165. package/dist/teams-chat.js +4 -2
  166. package/dist/telegram-lead.js +2 -1
  167. package/dist/telegram-live.js +2 -1
  168. package/dist/telegram-team.js +2 -1
  169. package/dist/telegram.js +17 -5
  170. package/dist/trusted-path.js +162 -0
  171. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  172. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  173. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  174. package/dist/tui/linux-x64/toolroll-tui +0 -0
  175. package/dist/tui-launch.js +282 -0
  176. package/dist/tui-source.js +5 -3
  177. package/dist/tui.js +2 -2
  178. package/dist/typed-words-schema.js +18 -0
  179. package/dist/webhooks.js +8 -4
  180. package/dist/welcome-facts.js +25 -17
  181. package/dist/work-index.js +126 -29
  182. package/dist/work-reads.js +279 -0
  183. package/dist/workspace-ui.js +5 -0
  184. package/package.json +4 -2
  185. package/scripts/crash-canary.mjs +1 -1
  186. package/scripts/pilot.mjs +1 -1
  187. package/scripts/provider-canary.mjs +5 -3
package/dist/store.js CHANGED
@@ -17,6 +17,15 @@ import { V158_ADDED_COLUMNS, V158_SCHEMA, V158_STEPS, LEAD_FAILURE_DETAILS, LEAD
17
17
  import { V157_SCHEMA, V157_STEPS } from "./chat-live-schema.js";
18
18
  import { V159_ADDED_COLUMNS, V159_SCHEMA, V159_STEPS } from "./one-step-chat-schema.js";
19
19
  import { V160_BACKFILL, V160_SCHEMA, V160_STEPS } from "./advanced-schema.js";
20
+ import { V161_SCHEMA, V161_STEPS } from "./flexible-schema.js";
21
+ import { V162_SCHEMA, V162_STEPS } from "./flexible-thread-schema.js";
22
+ import { V163_SCHEMA, V163_STEPS } from "./typed-words-schema.js";
23
+ import { V164_OBJECTS, V164_SCHEMA, V164_STEPS } from "./flexible-turns-schema.js";
24
+ import { V165_OBJECTS, V165_SCHEMA, V165_STEPS } from "./flexible-launch-schema.js";
25
+ import { V166_OBJECTS, V166_SCHEMA, V166_STEPS } from "./flexible-relay-schema.js";
26
+ import { V167_OBJECTS, V167_SCHEMA, V167_STEPS } from "./flexible-answers-schema.js";
27
+ import { V168_OBJECTS, V168_SCHEMA, V168_STEPS } from "./flexible-ship-schema.js";
28
+ import { endLapsedFlexible } from "./flexible.js";
20
29
  import { refArchived, taskArchived, taskCancelled } from "./task-archive.js";
21
30
  export { refArchived, taskArchived } from "./task-archive.js";
22
31
  import { CHAT_PROVIDERS, CHAT_SCHEMA } from "./contracts/chat-tables.js";
@@ -61,6 +70,7 @@ import { ACTIVITY_ONLY_KINDS } from "./needs-you.js";
61
70
  import { parseReviewContext, reviewContextCustodyProblem } from "./review-context.js";
62
71
  import { foldReview, manualReviewOnly } from "./proof.js";
63
72
  import { hashPassword, liveReleaseOf } from "./scope.js";
73
+ import { declareNewInstallSolo } from "./install-mode.js";
64
74
  import { currentLocalOwner, LOCAL_MODE_CONFINES, LOCAL_OWNER_LAPSED, localModeOn, localOwnerInFlight, localOwnerStandsNow } from "./local-owner.js";
65
75
  import { nightlyDebtHold } from "./nightly-github.js";
66
76
  import { releaseCiHoldOf, releaseCiRunningOf } from "./release-ci-hold.js";
@@ -819,7 +829,7 @@ export function checkSuitesOf(value) {
819
829
  }
820
830
  }
821
831
  const REGISTERED_AT_FILING = "again, as it was filed";
822
- export const SCHEMA_VERSION = 160;
832
+ export const SCHEMA_VERSION = 168;
823
833
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
824
834
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
825
835
  const V118_COORDINATOR_COLUMNS = [["task_ref", "coordinator_cid"], ["coordinator_event", "cid"], ["mcp_idempotency", "cid"], ["coordinator_proposal", "cid"]];
@@ -884,7 +894,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
884
894
  "fallback_config", "fallback_cycle", "fallback_transition",
885
895
  ]);
886
896
  const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
887
- export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160]);
897
+ export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168]);
888
898
  export const V119_ADDED_COLUMNS = Object.freeze({
889
899
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
890
900
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1427,7 +1437,7 @@ export { V156_STEPS };
1427
1437
  export { V157_STEPS };
1428
1438
  export { V158_STEPS };
1429
1439
  export { V159_STEPS };
1430
- export { V160_STEPS };
1440
+ export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS };
1431
1441
  export const RELEASE_ONCE_SCHEMA = `
1432
1442
  CREATE TABLE IF NOT EXISTS release_authority (
1433
1443
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -4205,7 +4215,7 @@ function initializeStore(db, file, options = {}) {
4205
4215
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4206
4216
  }
4207
4217
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4208
- const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db);
4218
+ const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db);
4209
4219
  if (missing !== null)
4210
4220
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4211
4221
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4547,6 +4557,46 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4547
4557
  }
4548
4558
  }
4549
4559
  step("advanced-preference");
4560
+ db.exec(V161_SCHEMA);
4561
+ const flexibleDamaged = flexibleTermsShapeProblem(db);
4562
+ if (flexibleDamaged !== null)
4563
+ throw new Error(`${file}: refusing to open — ${flexibleDamaged}`);
4564
+ step("flexible-terms");
4565
+ db.exec(V162_SCHEMA);
4566
+ const threadDamaged = flexibleThreadShapeProblem(db);
4567
+ if (threadDamaged !== null)
4568
+ throw new Error(`${file}: refusing to open — ${threadDamaged}`);
4569
+ step("flexible-thread");
4570
+ db.exec(V163_SCHEMA);
4571
+ const typedDamaged = typedByPersonShapeProblem(db);
4572
+ if (typedDamaged !== null)
4573
+ throw new Error(`${file}: refusing to open — ${typedDamaged}`);
4574
+ step("typed-by-person");
4575
+ db.exec(V164_SCHEMA);
4576
+ const turnsDamaged = flexibleTurnsShapeProblem(db);
4577
+ if (turnsDamaged !== null)
4578
+ throw new Error(`${file}: refusing to open — ${turnsDamaged}`);
4579
+ step("thread-turn");
4580
+ db.exec(V165_SCHEMA);
4581
+ const launchDamaged = flexibleLaunchShapeProblem(db);
4582
+ if (launchDamaged !== null)
4583
+ throw new Error(`${file}: refusing to open — ${launchDamaged}`);
4584
+ step("thread-launch");
4585
+ db.exec(V166_SCHEMA);
4586
+ const relayDamaged = flexibleRelayShapeProblem(db);
4587
+ if (relayDamaged !== null)
4588
+ throw new Error(`${file}: refusing to open — ${relayDamaged}`);
4589
+ step("thread-relay-call");
4590
+ db.exec(V167_SCHEMA);
4591
+ const answersDamaged = flexibleAnswersShapeProblem(db);
4592
+ if (answersDamaged !== null)
4593
+ throw new Error(`${file}: refusing to open — ${answersDamaged}`);
4594
+ step("thread-decision");
4595
+ db.exec(V168_SCHEMA);
4596
+ const shipDamaged = flexibleShipShapeProblem(db);
4597
+ if (shipDamaged !== null)
4598
+ throw new Error(`${file}: refusing to open — ${shipDamaged}`);
4599
+ step("flexible-ship");
4550
4600
  if (!fresh)
4551
4601
  reclaimDatabase(db, "migration");
4552
4602
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -7013,7 +7063,8 @@ export class Store {
7013
7063
  WHERE task_ref.repo = ? AND run.cost_usd IS NOT NULL
7014
7064
  AND run.provider_started_at >= ? AND run.provider_started_at < ?`)
7015
7065
  .get(repo, `${day}T00:00:00.000Z`, `${day}T23:59:59.999Z`);
7016
- if (Number(spent?.["total"] ?? 0) >= terms.dailyMeasuredCapMicrousd) {
7066
+ const threads = this.db.prepare("SELECT COALESCE(SUM(cost_microusd), 0) AS total FROM thread_turn WHERE repo = ? AND utc_day = ? AND status <> 'withdrawn'").get(repo, day);
7067
+ if (Number(spent?.["total"] ?? 0) + Number(threads?.["total"] ?? 0) >= terms.dailyMeasuredCapMicrousd) {
7017
7068
  return {
7018
7069
  ok: false,
7019
7070
  rail: "daily-dollars",
@@ -7076,6 +7127,7 @@ export class Store {
7076
7127
  .map(row => Number(row["id"]));
7077
7128
  for (const id of subscriptions)
7078
7129
  this.retirePushSubscription(id, "credential-rotation", now);
7130
+ endLapsedFlexible(this, { signer: approver }, by, now);
7079
7131
  }
7080
7132
  listApprovers() {
7081
7133
  return this.db
@@ -7137,6 +7189,7 @@ export class Store {
7137
7189
  this.recordPolicy(by, repo, "approval rules changed", rulesWords(before), rulesWords(next), now);
7138
7190
  if (isProtectedWork(next, []))
7139
7191
  endUnattendedGrants(this, { repo }, by, "project protected", now);
7192
+ endLapsedFlexible(this, { repo }, by, now);
7140
7193
  });
7141
7194
  }
7142
7195
  taskFiler(taskId) {
@@ -10406,12 +10459,22 @@ export class Store {
10406
10459
  const hours = (iso) => Math.max(0, Math.round((now.getTime() - Date.parse(String(iso))) / 3_600_000));
10407
10460
  return this.transact(() => {
10408
10461
  const families = this.taskFamiliesAdmitted(admittedRepos, false, { limit: 61 });
10409
- const taskRows = families.slice(0, 61).map(family => {
10462
+ const shown = families.slice(0, 61);
10463
+ const refs = new Map(this.db.prepare("SELECT * FROM task_ref WHERE backend = ? AND external_id IN (SELECT value FROM json_each(?))")
10464
+ .all(BUILT_IN, JSON.stringify(shown.map(family => family.current.id))).map(row => [String(row["external_id"]), readTaskRef(row)]));
10465
+ const results = new Map(this.db.prepare(`SELECT * FROM run WHERE id IN (SELECT MAX(id) FROM run WHERE task_ref IN (SELECT value FROM json_each(?))
10466
+ AND finished_at IS NOT NULL AND role IN ('builder','scout') GROUP BY task_ref)`)
10467
+ .all(JSON.stringify([...refs.values()].map(ref => ref.id))).map(row => readRun(row)).map(run => [run.taskRef, run]));
10468
+ const resultIds = JSON.stringify([...results.values()].map(run => run.id));
10469
+ const verdicts = new Map(this.db.prepare("SELECT * FROM proof_verdict WHERE run IN (SELECT value FROM json_each(?))").all(resultIds)
10470
+ .map(row => readProofVerdict(row)).map(verdict => [verdict.run, verdict]));
10471
+ const acceptances = new Set(this.db.prepare("SELECT run FROM proof_acceptance WHERE run IN (SELECT value FROM json_each(?))").all(resultIds).map(row => Number(row["run"])));
10472
+ const taskRows = shown.map(family => {
10410
10473
  const current = family.current;
10411
- const ref = this.lookupRef(current.id);
10412
- const run = this.runsFor(ref.id).find(one => one.finishedAt !== null && (one.role === "builder" || one.role === "scout"));
10413
- const proof = current.state === "done" && run !== undefined ? this.proofVerdictFor(run.id) : null;
10414
- return { family, current, ref, proof, accepted: run !== undefined && this.proofAcceptance(run.id) !== null };
10474
+ const ref = refs.get(current.id);
10475
+ const run = results.get(ref.id);
10476
+ const proof = current.state === "done" && run !== undefined ? verdicts.get(run.id) ?? null : null;
10477
+ return { family, current, ref, proof, accepted: run !== undefined && acceptances.has(run.id) };
10415
10478
  });
10416
10479
  const decisionRows = this.db
10417
10480
  .prepare(`SELECT decision.id AS id, decision.question AS question, decision.options AS options, task_ref.repo AS repo,
@@ -11615,6 +11678,7 @@ export class Store {
11615
11678
  const words = { providers: "allowed providers", models: "allowed models", tools: "allowed tools", ceiling: "permission ceiling" };
11616
11679
  for (const rule of ["providers", "models", "tools", "ceiling"])
11617
11680
  this.recordPolicy(by, null, `organisation policy: ${words[rule]}`, before[rule], after[rule], now);
11681
+ endLapsedFlexible(this, "all", by, now);
11618
11682
  return this.orgPolicy();
11619
11683
  });
11620
11684
  }
@@ -11738,6 +11802,9 @@ export class Store {
11738
11802
  reached: Number(row["reached"]) === 1, plan: row["plan"] == null ? null : String(row["plan"]), observedAt: String(row["observed_at"]),
11739
11803
  }));
11740
11804
  }
11805
+ spendBetween(from, to) {
11806
+ return spendItems(this.db, from, to);
11807
+ }
11741
11808
  monthSpend(now) {
11742
11809
  const month = monthOf(now);
11743
11810
  const items = spendItems(this.db, month.from, month.to);
@@ -15039,6 +15106,7 @@ export class Store {
15039
15106
  this.db
15040
15107
  .prepare("INSERT INTO approver (name, credential_hash, added_at, generation) VALUES (?, ?, ?, 1)")
15041
15108
  .run(name, credentialHash, now.toISOString());
15109
+ declareNewInstallSolo(this, name, now);
15042
15110
  return { ok: true };
15043
15111
  });
15044
15112
  }
@@ -15608,6 +15676,7 @@ export class Store {
15608
15676
  const after = this.projectNetwork(repo);
15609
15677
  const words = (one) => `${one.mode}${one.hosts.length === 0 ? "" : ` +${one.hosts.join(",")}`}${one.loopback === "proxy-only" ? " no-local" : ""}`;
15610
15678
  this.recordPolicy(by, repo, "network", words(before), words(after), now);
15679
+ endLapsedFlexible(this, { repo }, by, now);
15611
15680
  return { before, after };
15612
15681
  });
15613
15682
  }
@@ -18277,6 +18346,7 @@ export function initLocalMode(store, input) {
18277
18346
  return { ok: false, reason: "has-accounts" };
18278
18347
  store.handle.prepare("INSERT INTO local_mode (id, owner, generation, enabled, initialized_at, changed_at) VALUES (1, ?, 1, 1, ?, ?)").run(input.owner, stamp, stamp);
18279
18348
  store.recordAction({ at: stamp, actor: input.owner, repo: null, taskId: null, runId: null, action: "local mode on", outcome: "initialized", source: "access", detail: "a new install with no account, started at its own terminal: the owner has no password yet" });
18349
+ declareNewInstallSolo(store, input.owner, input.now);
18280
18350
  return { ok: true, owner: input.owner, generation: 1 };
18281
18351
  });
18282
18352
  }
@@ -18690,6 +18760,132 @@ export function resetAccountPassword(store, name, credentialHash, expectedGenera
18690
18760
  return { ok: true, generation: expectedGeneration + 1, leadTokens };
18691
18761
  });
18692
18762
  }
18763
+ function flexibleTermsShapeProblem(db) {
18764
+ const statements = V161_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18765
+ for (const [type, name] of [["table", "flexible_terms"], ["index", "flexible_terms_live"], ["trigger", "flexible_terms_written_once"]]) {
18766
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18767
+ if (row === undefined)
18768
+ return `the flexible_terms ${type} ${name} is missing`;
18769
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18770
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18771
+ return `the flexible_terms ${type} ${name} has an unknown shape`;
18772
+ }
18773
+ return null;
18774
+ }
18693
18775
  export function projectRowKnown(store, path) {
18694
18776
  return store.handle.prepare("SELECT 1 FROM project WHERE path = ?").get(path) !== undefined;
18695
18777
  }
18778
+ function flexibleThreadShapeProblem(db) {
18779
+ const statements = V162_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18780
+ for (const [type, name] of [["table", "flexible_thread"], ["index", "flexible_thread_repo"], ["trigger", "flexible_thread_written_once"]]) {
18781
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18782
+ if (row === undefined)
18783
+ return `the flexible_thread ${type} ${name} is missing`;
18784
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18785
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18786
+ return `the flexible_thread ${type} ${name} has an unknown shape`;
18787
+ }
18788
+ return null;
18789
+ }
18790
+ export function accountAccessOf(store, name) {
18791
+ const account = store.accountOf(name);
18792
+ return repo => account !== null && account.revokedAt === null && projectAccessAllows(account.projects, repo);
18793
+ }
18794
+ function typedByPersonShapeProblem(db) {
18795
+ const statements = V163_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18796
+ for (const [type, name] of [["table", "typed_by_person"], ["trigger", "typed_by_person_written_once"]]) {
18797
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18798
+ if (row === undefined)
18799
+ return `the typed_by_person ${type} ${name} is missing`;
18800
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18801
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18802
+ return `the typed_by_person ${type} ${name} has an unknown shape`;
18803
+ }
18804
+ return null;
18805
+ }
18806
+ export function markTypedByPerson(store, note, author, words, now, question = null) {
18807
+ const typed = (words ?? "").trim();
18808
+ if (typed === "" || typed.length > 8000)
18809
+ return false;
18810
+ const comment = "comment" in note ? note.comment : null, steer = "steer" in note ? note.steer : null;
18811
+ const saved = store.handle.prepare(comment !== null ? "SELECT note FROM diff_comment WHERE id = ?" : "SELECT note FROM task_steer WHERE id = ?").get(comment ?? steer);
18812
+ if (saved === undefined || !String(saved["note"]).includes(typed))
18813
+ return false;
18814
+ return Number(store.handle.prepare("INSERT INTO typed_by_person (comment, steer, author, words, question, typed_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING")
18815
+ .run(comment, steer, author, typed, question === null ? null : question.slice(0, 400) || null, now.toISOString()).changes) === 1;
18816
+ }
18817
+ export function typedNotesFor(store, taskId, cap) {
18818
+ const ref = store.handle.prepare("SELECT id FROM task_ref WHERE backend = ? AND external_id = ?").get(BUILT_IN, taskId);
18819
+ const rows = store.handle.prepare(`
18820
+ SELECT 'sent-back' AS kind, c.id AS id, c.author AS author, c.created_at AS at, t.words AS words, t.question AS question FROM diff_comment c
18821
+ JOIN diff_comment o ON (o.id = c.id OR o.superseded_by = c.id) AND o.note = c.note AND o.author = c.author
18822
+ JOIN typed_by_person t ON t.comment = o.id AND t.author = c.author
18823
+ WHERE c.consumed_by = ? AND c.reviewer_run IS NULL AND instr(c.note, t.words) > 0
18824
+ UNION ALL
18825
+ SELECT 'to-agent' AS kind, s.id AS id, s.author AS author, s.created_at AS at, t.words AS words, t.question AS question FROM task_steer s
18826
+ JOIN typed_by_person t ON t.steer = s.id AND t.author = s.author
18827
+ WHERE s.task_ref = ? AND s.authorship_state = 'verified' AND instr(s.note, t.words) > 0
18828
+ ORDER BY at DESC, id DESC LIMIT ?`).all(taskId, ref === undefined ? -1 : Number(ref["id"]), Math.max(0, cap));
18829
+ return rows.map(row => ({ kind: row["kind"] === "sent-back" ? "sent-back" : "to-agent", id: Number(row["id"]), author: String(row["author"]),
18830
+ at: String(row["at"]), note: String(row["words"]), question: row["question"] == null ? null : String(row["question"]) }));
18831
+ }
18832
+ function flexibleTurnsShapeProblem(db) {
18833
+ const statements = V164_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18834
+ for (const [type, name] of V164_OBJECTS) {
18835
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18836
+ if (row === undefined)
18837
+ return `the Flexible turns ${type} ${name} is missing`;
18838
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18839
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18840
+ return `the Flexible turns ${type} ${name} has an unknown shape`;
18841
+ }
18842
+ return null;
18843
+ }
18844
+ function flexibleLaunchShapeProblem(db) {
18845
+ const statements = V165_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18846
+ for (const [type, name] of V165_OBJECTS) {
18847
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18848
+ if (row === undefined)
18849
+ return `the Flexible launches ${type} ${name} is missing`;
18850
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18851
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18852
+ return `the Flexible launches ${type} ${name} has an unknown shape`;
18853
+ }
18854
+ return null;
18855
+ }
18856
+ function flexibleRelayShapeProblem(db) {
18857
+ const statements = V166_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18858
+ for (const [type, name] of V166_OBJECTS) {
18859
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18860
+ if (row === undefined)
18861
+ return `the Flexible relay calls ${type} ${name} is missing`;
18862
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18863
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18864
+ return `the Flexible relay calls ${type} ${name} has an unknown shape`;
18865
+ }
18866
+ return null;
18867
+ }
18868
+ function flexibleAnswersShapeProblem(db) {
18869
+ const statements = V167_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18870
+ for (const [type, name] of V167_OBJECTS) {
18871
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18872
+ if (row === undefined)
18873
+ return `the Flexible answers ${type} ${name} is missing`;
18874
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18875
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18876
+ return `the Flexible answers ${type} ${name} has an unknown shape`;
18877
+ }
18878
+ return null;
18879
+ }
18880
+ function flexibleShipShapeProblem(db) {
18881
+ const statements = V168_SCHEMA.split(/;\s*\n(?=CREATE )/).map(one => one.trim().replace(/;$/, "")).filter(one => one !== "");
18882
+ for (const [type, name] of V168_OBJECTS) {
18883
+ const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
18884
+ if (row === undefined)
18885
+ return `the Flexible ship ${type} ${name} is missing`;
18886
+ const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} IF NOT EXISTS ${name}\\b`).test(one));
18887
+ if (want === undefined || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(want).trim())
18888
+ return `the Flexible ship ${type} ${name} has an unknown shape`;
18889
+ }
18890
+ return null;
18891
+ }
@@ -0,0 +1,64 @@
1
+ const SECTIONS = ["summary", "changes", "checks"];
2
+ const ANCHOR = /^[A-Za-z0-9_-][A-Za-z0-9_.:-]{0,159}$/;
3
+ const REFUSAL = /^[a-z][a-z-]{0,31}$/;
4
+ const ID = /^[A-Za-z0-9._~%-]{1,200}$/;
5
+ const validRun = (run) => typeof run === "number" && Number.isSafeInteger(run) && run > 0;
6
+ const hashOf = (anchor) => anchor != null && ANCHOR.test(anchor) ? `#${anchor}` : "";
7
+ export function taskLinkOf(link) {
8
+ const path = `/t/${encodeURIComponent(link.task)}`;
9
+ const hash = hashOf(link.anchor);
10
+ if (link.record === true) {
11
+ if (validRun(link.run))
12
+ return `/r/${link.run}?record=1${hash}`;
13
+ const query = new URLSearchParams();
14
+ if (link.revision != null && link.revision !== "")
15
+ query.set("version", link.revision);
16
+ query.set("tab", "record");
17
+ return `${path}?${query.toString()}${hash === "" ? "#record" : hash}`;
18
+ }
19
+ const query = [];
20
+ if (link.revision != null && link.revision !== "")
21
+ query.push(`version=${encodeURIComponent(link.revision)}`);
22
+ const section = link.section != null && SECTIONS.includes(link.section) ? link.section : null;
23
+ const result = validRun(link.run) || section !== null || link.result === true;
24
+ if (result) {
25
+ query.push("tab=result");
26
+ if (validRun(link.run))
27
+ query.push(`run=${link.run}`);
28
+ if (section !== null && section !== "summary")
29
+ query.push(`section=${section}`);
30
+ }
31
+ if (link.feedback?.noted === true)
32
+ query.push("noted=1");
33
+ if (link.feedback?.refused != null && REFUSAL.test(link.feedback.refused))
34
+ query.push(`refused=${link.feedback.refused}`);
35
+ return `${path}${query.length === 0 ? "" : `?${query.join("&")}`}${hash}`;
36
+ }
37
+ export function taskLinkFromLegacy(href) {
38
+ let url;
39
+ try {
40
+ url = new URL(href, "http://toolroll.local");
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ if (url.origin !== "http://toolroll.local" || !href.startsWith("/"))
46
+ return null;
47
+ const anchor = url.hash === "" ? null : decodeURIComponent(url.hash.slice(1));
48
+ const section = (raw) => raw !== null && SECTIONS.includes(raw) ? raw : null;
49
+ const runOf = (raw) => raw !== null && /^[1-9][0-9]{0,14}$/.test(raw) ? Number(raw) : null;
50
+ if (url.pathname === "/review") {
51
+ const task = url.searchParams.get("result");
52
+ if (task === null || !ID.test(encodeURIComponent(task)))
53
+ return null;
54
+ return taskLinkOf({ task, run: runOf(url.searchParams.get("run")), section: section(url.searchParams.get("tab")), anchor, result: true,
55
+ feedback: { noted: url.searchParams.get("noted") !== null, refused: url.searchParams.get("refused") } });
56
+ }
57
+ if (url.pathname === "/chat") {
58
+ const task = url.searchParams.get("task"), run = runOf(url.searchParams.get("result"));
59
+ if (task === null || run === null || !ID.test(encodeURIComponent(task)))
60
+ return null;
61
+ return taskLinkOf({ task, run, section: section(url.searchParams.get("tab")), anchor });
62
+ }
63
+ return null;
64
+ }
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) {