saarthiclaw 0.1.0 → 0.2.1

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 (35) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +49 -1
  3. package/dist/chunks/{chunk-GVDXGKLD.js → chunk-4CNBITFA.js} +39 -15
  4. package/dist/chunks/{chunk-GNAQO3JX.js → chunk-4YYY2YOT.js} +9 -5
  5. package/dist/chunks/{chunk-LLHZUSMZ.js → chunk-5WH3FNFK.js} +1 -0
  6. package/dist/chunks/chunk-E4DRW4AW.js +126 -0
  7. package/dist/chunks/chunk-EG5A2Q6X.js +121 -0
  8. package/dist/chunks/{chunk-3UTSY2MH.js → chunk-GSBUJPPF.js} +9 -12
  9. package/dist/chunks/{chunk-DORYMXNC.js → chunk-OICPXSO2.js} +1 -1
  10. package/dist/chunks/{chunk-4MPWZPGX.js → chunk-OS5GVLKA.js} +1 -219
  11. package/dist/chunks/chunk-QFVMJJQY.js +411 -0
  12. package/dist/chunks/{chunk-HNAZBEDV.js → chunk-QRAFFI5V.js} +6 -4
  13. package/dist/chunks/chunk-R7ID2QVW.js +39 -0
  14. package/dist/chunks/chunk-SKYTL7AH.js +83 -0
  15. package/dist/chunks/{chunk-EWADWZYM.js → chunk-VAP6FVF5.js} +21 -17
  16. package/dist/chunks/chunk-ZXVP7JFV.js +232 -0
  17. package/dist/chunks/client-5WRI2PBK.js +18 -0
  18. package/dist/chunks/context-AP3U34DQ.js +20 -0
  19. package/dist/chunks/{doctor-333IEMCL.js → doctor-O3R2YTRO.js} +21 -0
  20. package/dist/chunks/{history-IWDIOWLB.js → history-FANJN33X.js} +4 -3
  21. package/dist/chunks/{init-Z4YC3G7V.js → init-GCJNYE3Y.js} +17 -50
  22. package/dist/chunks/orchestrator-4SMA442I.js +24 -0
  23. package/dist/chunks/orchestrator-CYIGQH74.js +32 -0
  24. package/dist/chunks/orchestrator-L4TOOHXY.js +23 -0
  25. package/dist/chunks/{session-UUHCIT66.js → session-FPFJMS7Y.js} +2 -2
  26. package/dist/chunks/store-KW257WIV.js +40 -0
  27. package/dist/chunks/sync-S2A65FIE.js +21 -0
  28. package/dist/chunks/team-OFNBRXVP.js +378 -0
  29. package/dist/chunks/{telegram-X36RUESQ.js → telegram-LPSIQBQX.js} +24 -11
  30. package/dist/chunks/{wakeup-I7FQO5BS.js → wakeup-M5EIP54K.js} +57 -16
  31. package/dist/index.js +62 -13
  32. package/package.json +4 -2
  33. package/dist/chunks/orchestrator-QCIY6FLH.js +0 -17
  34. package/dist/chunks/orchestrator-SDAA5TOH.js +0 -18
  35. package/dist/chunks/orchestrator-WXGJJEJW.js +0 -26
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  All notable changes to this project are documented here. This project follows [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## 0.2.1 — 2026-11-18
6
+
7
+ ### Changed
8
+ - **Keys are saved per project folder.** Two folders on one computer (for example the Admin's copy and a teammate's copy during a demo) keep separate keys; no `SAARTHICLAW_HOME` trick needed. A copied project folder never inherits someone else's key: it asks for its own `team connect`. Keys saved by 0.2.0 must be connected once more.
9
+ - After sending changes for approval, the agent offers to **wait right there** and applies them as soon as the Admin approves — one command instead of `agent` + `team sync --wait`.
10
+ - `team connect` asks before switching a folder to a different person (wrong key pasted), warns when the folder has no AI key yet, and prints the next command for your level. On a fresh dashboard it asks to *link* the folder (not "update").
11
+ - `team invite <name>` for someone already on the team offers a new key instead of creating a duplicate member.
12
+
13
+
14
+
15
+ ### Added
16
+ - **Team mode** with the SaarthiClaw web dashboard: `saarthiclaw team connect | status | sync | suggest | invite | inbox | disconnect`, plus a 👥 Team entry in the main menu.
17
+ - Permission levels decide what happens after Agent / Plan / Ask `--save`:
18
+ - Admin and Trusted review and apply locally; the result is logged on the dashboard.
19
+ - Needs approval sends the changes to the Admin, and `team sync` applies the approved ones.
20
+ - Suggest only sends a suggestion instead.
21
+ - `team sync --wait` waits for the Admin's decision and applies as soon as it arrives.
22
+ - Approved changes are applied only if the file still matches the version the agent saw (SHA-256), so an approval never overwrites newer work.
23
+ - `doctor` reports the team connection; `init` mentions team mode.
24
+ - New audit event `submitted` (sent for approval; nothing written).
25
+
26
+ ### Changed
27
+ - Agent, Plan and Ask `--save` share one final review/apply step (`team/finalize.ts`); solo behaviour is unchanged.
28
+ - Telegram remote control is limited to the Admin and Trusted members when a project is in team mode.
29
+
5
30
  ## 0.1.0 — 2026-11-17
6
31
 
7
32
  First public release on npm.
package/README.md CHANGED
@@ -20,6 +20,7 @@ npx saarthiclaw # wake it up
20
20
  - [The modes](#the-modes)
21
21
  - [How approval works](#how-approval-works)
22
22
  - [Safety model](#safety-model)
23
+ - [Working with a team](#working-with-a-team)
23
24
  - [Configuration](#configuration)
24
25
  - [Command reference](#command-reference)
25
26
  - [Telegram setup](#telegram-setup)
@@ -144,6 +145,47 @@ If applying a file change fails half-way, every file change from that batch is *
144
145
  | Audit log | Every staged / approved / rejected / applied / failed event is appended to `.saarthiclaw/logs/actions.jsonl` (timestamp, mode, type, path, risk, status — never file contents or commands). View it with `saarthiclaw history`. |
145
146
  | Keys never logged | API keys are masked in `init`, `doctor` and `--debug` output. |
146
147
 
148
+ ## Working with a team
149
+
150
+ Working alone needs none of this. With a team, SaarthiClaw connects to the **SaarthiClaw web dashboard** (a separate app the Admin runs). One person is the **Admin**; everyone else gets their own access key and a permission level the Admin can change at any time.
151
+
152
+ | Level | What happens when the agent finishes |
153
+ | --- | --- |
154
+ | **Admin** | You review and apply in your terminal, as in solo mode. Each applied change is also logged on the dashboard. |
155
+ | **Trusted** | Same as Admin: you approve your own changes; they are logged on the dashboard. |
156
+ | **Needs approval** (default) | Nothing is written. The changes go to the dashboard; the Admin approves or rejects each one. Then `saarthiclaw team sync` applies the approved ones on your computer. |
157
+ | **Suggest only** | Ask and Plan work; the agent can't change code. Your idea is sent as a suggestion instead. |
158
+
159
+ **Admin, once:**
160
+ ```bash
161
+ npx saarthiclaw team connect http://127.0.0.1:3000 # paste the Admin key the dashboard printed on its first `npm start`
162
+ npx saarthiclaw team invite Riya --level needs-approval # prints Riya's one-time key
163
+ ```
164
+
165
+ **Each developer, once (in their own copy of the project):**
166
+ ```bash
167
+ npx saarthiclaw team connect http://<admin-address>:3000 # paste your key
168
+ ```
169
+
170
+ **Day to day (Needs approval) — one command:**
171
+ ```bash
172
+ npx saarthiclaw agent "validate todo text"
173
+ # → review the diff → "Send all for approval" → "Wait here?" Yes
174
+ # the Admin approves on the dashboard → the change is applied here a few seconds later
175
+ ```
176
+ Closed the terminal before the Admin decided? `npx saarthiclaw team sync` applies whatever was approved since.
177
+
178
+ How it stays safe:
179
+ - **The dashboard never touches files.** It stores the proposal and the decision; your own terminal applies it.
180
+ - **No overwriting newer work.** Each proposal carries a hash of the file it was based on. If the file changed since, `team sync` does not apply it and reports it as failed; ask the agent again.
181
+ - **Keys stay out of the project.** They are saved in `~/.saarthiclaw/credentials.json` (owner-only), never in the repo, and **per project folder**: two folders on one computer can belong to two people (handy for a demo), and a copied folder never inherits someone else's key — it needs its own `team connect`. `SAARTHICLAW_TEAM_KEY` overrides it for CI.
182
+ - **Levels are checked on the server** on every request; a revoked key or a paused project stops changes immediately.
183
+ - Approved shell commands still ask you once more before running (or pass `--allow-shell`).
184
+
185
+ Use Git for the rest as usual: commit what `team sync` applied and open a pull request. For extra safety, protect the main branch on GitHub too.
186
+
187
+ > Friends on other computers can't reach `127.0.0.1`. Start the dashboard with `HOST=0.0.0.0` and share your LAN address, or host it behind HTTPS.
188
+
147
189
  ## Configuration
148
190
 
149
191
  Resolution order, first match wins per key:
@@ -201,6 +243,13 @@ Example:
201
243
  | `saarthiclaw agent "<task>"` | Agent mode with the task pre-filled |
202
244
  | `saarthiclaw telegram` | Run the Telegram bot until Ctrl+C |
203
245
  | `saarthiclaw history [--last N]` | Pretty-print the audit log (default 20) |
246
+ | `saarthiclaw team` / `team status` | Solo or team; your level; what is waiting |
247
+ | `saarthiclaw team connect [url]` (alias `join`) | Link this project to a dashboard with your key |
248
+ | `saarthiclaw team sync [--wait] [--yes]` | Apply your changes the Admin approved; show rejections. `--wait` keeps polling until everything is decided |
249
+ | `saarthiclaw team suggest "<idea>"` | Send an idea to the Admin |
250
+ | `saarthiclaw team invite <name> [--level trusted\|needs-approval\|suggest-only]` | (Admin) add a developer, print their one-time key |
251
+ | `saarthiclaw team inbox` | (Admin) suggestions you forwarded to the agent; run the agent on one |
252
+ | `saarthiclaw team disconnect` (alias `leave`) | Back to solo mode |
204
253
 
205
254
  Global options: `--cwd <path>`, `--model <id>`, `--allow-shell`, `--debug`, `--no-banner`, `-v/--version`, `-h/--help`.
206
255
 
@@ -248,7 +297,6 @@ No. That is the whole point.
248
297
 
249
298
  ## Roadmap
250
299
 
251
- - Web dashboard with Admin/Member keys and role-based access
252
300
  - WhatsApp remote mode
253
301
  - Database-backed history (the audit trail is already an event subscriber, so it can be swapped)
254
302
 
@@ -1,14 +1,18 @@
1
1
  import {
2
- ToolExecutor,
3
2
  createAgentTools,
3
+ finalizeStaged,
4
4
  finishOnLastStep,
5
5
  generateWithProgress,
6
- renderTerminalMarkdown,
7
- reportApply
8
- } from "./chunk-4MPWZPGX.js";
6
+ renderTerminalMarkdown
7
+ } from "./chunk-QFVMJJQY.js";
9
8
  import {
10
- runApprovalFlow
11
- } from "./chunk-HNAZBEDV.js";
9
+ ToolExecutor
10
+ } from "./chunk-OS5GVLKA.js";
11
+ import {
12
+ assertProjectOpen,
13
+ describeTeamMode,
14
+ getTeamContext
15
+ } from "./chunk-SKYTL7AH.js";
12
16
  import {
13
17
  RunCancelledError
14
18
  } from "./chunk-HGBZ55ND.js";
@@ -16,7 +20,7 @@ import {
16
20
  agentConfigFrom,
17
21
  createTracker,
18
22
  instructionsFor
19
- } from "./chunk-GNAQO3JX.js";
23
+ } from "./chunk-4YYY2YOT.js";
20
24
  import {
21
25
  AI_MAX_RETRIES
22
26
  } from "./chunk-BTFIQWAE.js";
@@ -24,24 +28,47 @@ import {
24
28
  // modes/agent/orchestrator.ts
25
29
  import chalk from "chalk";
26
30
  import { stepCountIs, ToolLoopAgent } from "ai";
27
- async function runAgentMode(session, presetTask) {
31
+ async function runAgentMode(session, presetTask, modeOpts = {}) {
28
32
  console.log(chalk.bold("\n🕵️ Agent Mode\n"));
29
33
  console.log(chalk.dim("The agent stages changes; nothing is written until you approve.\n"));
34
+ const team = await getTeamContext(session);
35
+ const banner = describeTeamMode(team);
36
+ if (banner) console.log(chalk.cyan(banner) + "\n");
37
+ assertProjectOpen(team);
38
+ if (team.mode === "suggest_only") {
39
+ const preset = presetTask?.trim() ?? "";
40
+ let idea = preset;
41
+ if (preset.length >= 10) {
42
+ const send = await session.prompter.confirm({ message: "Your level is Suggest only, so the agent can't change code. Send this to the Admin as a suggestion?", initialValue: true });
43
+ if (!send) return;
44
+ } else {
45
+ idea = (await session.prompter.text({
46
+ message: "Your level is Suggest only. What would you like to suggest to the Admin?",
47
+ placeholder: "Describe the change you'd like…",
48
+ validate: (v) => v.trim().length >= 10 ? void 0 : "Please write at least 10 characters"
49
+ })).trim();
50
+ }
51
+ await team.client.suggest(idea.slice(0, 500));
52
+ console.log(chalk.green("\n💡 Suggestion sent. The Admin sees it on the dashboard under Suggestions.\n"));
53
+ return;
54
+ }
30
55
  const task = presetTask?.trim() || (await session.prompter.text({
31
56
  message: "What should the agent do?",
32
57
  placeholder: "A concrete task for this codebase…",
33
58
  validate: (v) => v.trim() ? void 0 : "Please describe a task"
34
59
  })).trim();
35
60
  let allowShell = session.config.allowShellExecution;
36
- if (!allowShell) {
61
+ if (!allowShell && !modeOpts.send) {
37
62
  allowShell = await session.prompter.confirm({
38
63
  message: "Allow shell commands in this session? (each command still needs your approval)",
39
64
  initialValue: false
40
65
  });
41
66
  }
42
- await runAgentTask(session, task, { allowShell });
67
+ await runAgentTask(session, task, { allowShell, autoSend: modeOpts.send });
43
68
  }
44
69
  async function runAgentTask(session, task, opts) {
70
+ const team = await getTeamContext(session);
71
+ assertProjectOpen(team);
45
72
  const tracker = createTracker(session, "agent");
46
73
  const executor = new ToolExecutor(
47
74
  tracker,
@@ -60,11 +87,8 @@ async function runAgentTask(session, task, opts) {
60
87
  });
61
88
  const { text } = await generateWithProgress(agent, task, "Agent is thinking…");
62
89
  if (text.trim()) console.log("\n" + renderTerminalMarkdown(text) + "\n");
63
- const approved = await runApprovalFlow(tracker, session.prompter, { root: session.root });
64
- if (!approved) return { text, approved: false };
65
- const result = executor.applyApprovedFromTracker();
66
- reportApply(result);
67
- return { text, approved: true, result };
90
+ const outcome = await finalizeStaged(session, tracker, executor, { task, summary: text, autoSend: opts.autoSend });
91
+ return { text, ...outcome };
68
92
  } catch (e) {
69
93
  const discarded = tracker.discardPending(e instanceof RunCancelledError ? "cancelled" : "aborted");
70
94
  if (discarded > 0) {
@@ -1,3 +1,6 @@
1
+ import {
2
+ attachAuditLog
3
+ } from "./chunk-5WH3FNFK.js";
1
4
  import {
2
5
  isSecretPath
3
6
  } from "./chunk-XTVJWMUH.js";
@@ -5,9 +8,6 @@ import {
5
8
  getAgentModel,
6
9
  mapAiError
7
10
  } from "./chunk-BTFIQWAE.js";
8
- import {
9
- attachAuditLog
10
- } from "./chunk-LLHZUSMZ.js";
11
11
 
12
12
  // modes/session.ts
13
13
  import chalk from "chalk";
@@ -267,7 +267,8 @@ var STATUS_EVENT = {
267
267
  approved: "approved",
268
268
  rejected: "rejected",
269
269
  applied: "applied",
270
- failed: "failed"
270
+ failed: "failed",
271
+ submitted: "submitted"
271
272
  };
272
273
  var ActionTracker = class {
273
274
  constructor(mode = "agent") {
@@ -343,7 +344,10 @@ function createSession(opts) {
343
344
  config,
344
345
  prompter: opts.prompter,
345
346
  debug: Boolean(opts.debug),
346
- model: opts.model ?? (() => getAgentModel({ apiKey: config.openrouterApiKey, model: config.model }))
347
+ model: opts.model ?? (() => getAgentModel({ apiKey: config.openrouterApiKey, model: config.model })),
348
+ teamFetch: opts.teamFetch,
349
+ env: opts.env,
350
+ teamPollMs: opts.teamPollMs
347
351
  };
348
352
  }
349
353
  function hasWebTools(session) {
@@ -141,6 +141,7 @@ export {
141
141
  maxRisk,
142
142
  classifyAction,
143
143
  auditLogPath,
144
+ createAuditLogger,
144
145
  attachAuditLog,
145
146
  readAuditLog
146
147
  };
@@ -0,0 +1,126 @@
1
+ import {
2
+ UserFacingError
3
+ } from "./chunk-G6GCAEKE.js";
4
+ import {
5
+ userConfigDir
6
+ } from "./chunk-2GDAWRT7.js";
7
+ import {
8
+ projectStateDir
9
+ } from "./chunk-MMIJKDOU.js";
10
+
11
+ // team/store.ts
12
+ import crypto from "node:crypto";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ var KEY_PATTERN = /^sc_[am]_[a-f0-9]{8}_[a-f0-9]{32}$/;
16
+ function sha256Hex(data) {
17
+ return crypto.createHash("sha256").update(data).digest("hex");
18
+ }
19
+ function teamFile(root) {
20
+ return path.join(projectStateDir(root), "team.json");
21
+ }
22
+ function syncStateFile(root) {
23
+ return path.join(projectStateDir(root), "team-sync.json");
24
+ }
25
+ function credentialsFile(env = process.env) {
26
+ return path.join(userConfigDir(env), "credentials.json");
27
+ }
28
+ function normalizeServer(input) {
29
+ const raw = input.trim();
30
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) && !/^https?:\/\//i.test(raw)) {
31
+ throw new UserFacingError("The dashboard address must start with http:// or https://");
32
+ }
33
+ let url;
34
+ try {
35
+ url = new URL(/^https?:\/\//i.test(raw) ? raw : `http://${raw}`);
36
+ } catch {
37
+ throw new UserFacingError(`"${input}" is not a valid dashboard address.`, "Example: http://127.0.0.1:3000 or https://team.example.com");
38
+ }
39
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
40
+ throw new UserFacingError("The dashboard address must start with http:// or https://");
41
+ }
42
+ return `${url.protocol}//${url.host}`;
43
+ }
44
+ function readJson(file) {
45
+ try {
46
+ return JSON.parse(fs.readFileSync(file, "utf8"));
47
+ } catch {
48
+ return void 0;
49
+ }
50
+ }
51
+ function writeJson(file, data, mode) {
52
+ fs.mkdirSync(path.dirname(file), { recursive: true });
53
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode });
54
+ if (mode !== void 0) {
55
+ try {
56
+ fs.chmodSync(file, mode);
57
+ } catch {
58
+ }
59
+ }
60
+ }
61
+ function readTeamLink(root, env = process.env) {
62
+ const link = readJson(teamFile(root));
63
+ const override = env.SAARTHICLAW_TEAM_SERVER?.trim();
64
+ if (override) return { ...link ?? { connectedAt: (/* @__PURE__ */ new Date()).toISOString() }, server: normalizeServer(override) };
65
+ if (!link || typeof link.server !== "string" || !link.server) return void 0;
66
+ return link;
67
+ }
68
+ function writeTeamLink(root, link) {
69
+ writeJson(teamFile(root), link);
70
+ }
71
+ function removeTeamLink(root) {
72
+ fs.rmSync(teamFile(root), { force: true });
73
+ fs.rmSync(syncStateFile(root), { force: true });
74
+ }
75
+ function credentialId(server, root) {
76
+ const abs = path.resolve(root);
77
+ return `${server} ${process.platform === "win32" ? abs.toLowerCase() : abs}`;
78
+ }
79
+ function readKey(server, root, env = process.env) {
80
+ const fromEnv = env.SAARTHICLAW_TEAM_KEY?.trim();
81
+ if (fromEnv) return fromEnv;
82
+ const creds = readJson(credentialsFile(env)) ?? {};
83
+ const k = creds[credentialId(server, root)]?.key;
84
+ return typeof k === "string" && k ? k : void 0;
85
+ }
86
+ function saveKey(server, root, key, env = process.env) {
87
+ const file = credentialsFile(env);
88
+ const creds = readJson(file) ?? {};
89
+ creds[credentialId(server, root)] = { key, savedAt: (/* @__PURE__ */ new Date()).toISOString() };
90
+ writeJson(file, creds, 384);
91
+ return file;
92
+ }
93
+ function removeKey(server, root, env = process.env) {
94
+ const file = credentialsFile(env);
95
+ const creds = readJson(file);
96
+ if (!creds) return;
97
+ const id = credentialId(server, root);
98
+ if (!(id in creds)) return;
99
+ delete creds[id];
100
+ writeJson(file, creds, 384);
101
+ }
102
+ function readSyncState(root) {
103
+ const s = readJson(syncStateFile(root));
104
+ return { seen: Array.isArray(s?.seen) ? s.seen.filter((n) => Number.isInteger(n)).slice(-2e3) : [], lastSyncAt: s?.lastSyncAt };
105
+ }
106
+ function writeSyncState(root, state) {
107
+ writeJson(syncStateFile(root), { seen: state.seen.slice(-2e3), lastSyncAt: state.lastSyncAt });
108
+ }
109
+
110
+ export {
111
+ KEY_PATTERN,
112
+ sha256Hex,
113
+ teamFile,
114
+ syncStateFile,
115
+ credentialsFile,
116
+ normalizeServer,
117
+ readTeamLink,
118
+ writeTeamLink,
119
+ removeTeamLink,
120
+ credentialId,
121
+ readKey,
122
+ saveKey,
123
+ removeKey,
124
+ readSyncState,
125
+ writeSyncState
126
+ };
@@ -0,0 +1,121 @@
1
+ import {
2
+ UserFacingError
3
+ } from "./chunk-G6GCAEKE.js";
4
+
5
+ // team/client.ts
6
+ var LEVEL_LABEL = {
7
+ admin: "Admin",
8
+ trusted: "Trusted",
9
+ needs_approval: "Needs approval",
10
+ suggest_only: "Suggest only"
11
+ };
12
+ var TeamApiError = class extends UserFacingError {
13
+ constructor(message, status, code, hint) {
14
+ super(message, hint);
15
+ this.status = status;
16
+ this.code = code;
17
+ this.name = "TeamApiError";
18
+ }
19
+ status;
20
+ code;
21
+ };
22
+ var TeamNetworkError = class extends UserFacingError {
23
+ constructor(server, detail) {
24
+ super(
25
+ `Can't reach the team dashboard at ${server}.`,
26
+ `${detail}
27
+ Check that the dashboard is running (\`npm start\` in saarthiclaw-web) and that this computer can reach that address.`
28
+ );
29
+ this.name = "TeamNetworkError";
30
+ }
31
+ };
32
+ var HINTS = {
33
+ INVALID_KEY: "Ask the Admin for a new key, then run `saarthiclaw team connect` again.",
34
+ SUGGEST_ONLY: 'Use `saarthiclaw team suggest "your idea"` — the Admin decides whether to pass it to the agent.',
35
+ PROJECT_LOCKED: "Ask the Admin to set the project back to Active on the dashboard.",
36
+ NO_PROJECT: "The Admin links the project by running `saarthiclaw team connect` inside the project folder.",
37
+ LOCKED_OUT: "Too many wrong keys were tried from this network. Wait, then check the key."
38
+ };
39
+ var TeamClient = class {
40
+ constructor(server, key, fetchImpl = (input, init) => fetch(input, init), timeoutMs = 2e4) {
41
+ this.server = server;
42
+ this.key = key;
43
+ this.fetchImpl = fetchImpl;
44
+ this.timeoutMs = timeoutMs;
45
+ }
46
+ server;
47
+ key;
48
+ fetchImpl;
49
+ timeoutMs;
50
+ async call(method, pathname, body) {
51
+ let response;
52
+ try {
53
+ response = await this.fetchImpl(`${this.server}/api/cli${pathname}`, {
54
+ method,
55
+ headers: {
56
+ Authorization: `Bearer ${this.key}`,
57
+ Accept: "application/json",
58
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
59
+ },
60
+ body: body === void 0 ? void 0 : JSON.stringify(body),
61
+ signal: AbortSignal.timeout(this.timeoutMs)
62
+ });
63
+ } catch (e) {
64
+ const err = e;
65
+ const detail = err.name === "TimeoutError" ? `No answer within ${Math.round(this.timeoutMs / 1e3)} seconds.` : err.cause?.code ? `${err.cause.code}${err.cause.message ? `: ${err.cause.message}` : ""}` : err.message ?? String(e);
66
+ throw new TeamNetworkError(this.server, detail);
67
+ }
68
+ let payload;
69
+ try {
70
+ payload = await response.json();
71
+ } catch {
72
+ payload = void 0;
73
+ }
74
+ if (!response.ok || !payload?.ok) {
75
+ const code = payload?.error?.code ?? `HTTP_${response.status}`;
76
+ let message = payload?.error?.message ?? `The dashboard answered with HTTP ${response.status}.`;
77
+ const fields = payload?.error?.fields;
78
+ if (fields) message += " " + Object.entries(fields).map(([k, v]) => `${k}: ${v}`).join("; ");
79
+ if (!payload && response.status === 404) message = "This address does not look like a SaarthiClaw dashboard (no /api/cli).";
80
+ throw new TeamApiError(message, response.status, code, HINTS[code]);
81
+ }
82
+ return payload.data;
83
+ }
84
+ whoami() {
85
+ return this.call("GET", "/whoami");
86
+ }
87
+ pushProject(snapshot) {
88
+ return this.call("POST", "/project", snapshot);
89
+ }
90
+ propose(body) {
91
+ return this.call("POST", "/proposals", body);
92
+ }
93
+ recordApplied(body) {
94
+ return this.call("POST", "/applied", body);
95
+ }
96
+ myActions() {
97
+ return this.call("GET", "/actions");
98
+ }
99
+ reportResult(id, ok, message) {
100
+ return this.call("POST", `/actions/${id}/result`, { ok, message: message.slice(0, 500) });
101
+ }
102
+ suggest(message) {
103
+ return this.call("POST", "/suggestions", { message });
104
+ }
105
+ inbox() {
106
+ return this.call("GET", "/inbox");
107
+ }
108
+ inboxDone(id) {
109
+ return this.call("POST", `/inbox/${id}/done`);
110
+ }
111
+ invite(name, permissionLevel, regenerate = false) {
112
+ return this.call("POST", "/members", { name, permissionLevel, ...regenerate ? { regenerate: true } : {} });
113
+ }
114
+ };
115
+
116
+ export {
117
+ LEVEL_LABEL,
118
+ TeamApiError,
119
+ TeamNetworkError,
120
+ TeamClient
121
+ };
@@ -1,24 +1,23 @@
1
1
  import {
2
2
  createWebTools
3
- } from "./chunk-DORYMXNC.js";
3
+ } from "./chunk-OICPXSO2.js";
4
4
  import {
5
- ToolExecutor,
6
5
  createReadOnlyTools,
7
6
  dedupeReadOnlyTools,
7
+ finalizeStaged,
8
8
  finishOnLastStep,
9
9
  generateWithProgress,
10
- renderTerminalMarkdown,
11
- reportApply
12
- } from "./chunk-4MPWZPGX.js";
10
+ renderTerminalMarkdown
11
+ } from "./chunk-QFVMJJQY.js";
13
12
  import {
14
- runApprovalFlow
15
- } from "./chunk-HNAZBEDV.js";
13
+ ToolExecutor
14
+ } from "./chunk-OS5GVLKA.js";
16
15
  import {
17
16
  agentConfigFrom,
18
17
  createTracker,
19
18
  instructionsFor,
20
19
  readOnlyAgentConfig
21
- } from "./chunk-GNAQO3JX.js";
20
+ } from "./chunk-4YYY2YOT.js";
22
21
  import {
23
22
  AI_MAX_RETRIES
24
23
  } from "./chunk-BTFIQWAE.js";
@@ -87,10 +86,8 @@ async function saveAnswer(session, filename, question, answer) {
87
86
  const target = path.join(session.root, filename.trim());
88
87
  if (fs.existsSync(target)) executor.modifyFile(filename.trim(), content);
89
88
  else executor.createFile(filename.trim(), content);
90
- const ok = await runApprovalFlow(tracker, session.prompter, { root: session.root });
91
- if (!ok) return false;
92
- reportApply(executor.applyApprovedFromTracker());
93
- return true;
89
+ const outcome = await finalizeStaged(session, tracker, executor, { task: `Save the answer to "${question.slice(0, 200)}" as ${filename.trim()}` });
90
+ return outcome.approved;
94
91
  } catch (e) {
95
92
  tracker.discardPending("aborted");
96
93
  throw e;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  clipOutput
3
- } from "./chunk-4MPWZPGX.js";
3
+ } from "./chunk-OS5GVLKA.js";
4
4
 
5
5
  // modes/plan/web-tools.ts
6
6
  import { tool } from "ai";