saarthiclaw 0.1.0 → 0.2.2

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 (36) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +49 -1
  3. package/dist/chunks/chunk-3UFD5346.js +126 -0
  4. package/dist/chunks/{chunk-LLHZUSMZ.js → chunk-5WH3FNFK.js} +1 -0
  5. package/dist/chunks/chunk-DSQDVSZS.js +411 -0
  6. package/dist/chunks/chunk-E4DRW4AW.js +126 -0
  7. package/dist/chunks/chunk-EG5A2Q6X.js +121 -0
  8. package/dist/chunks/{chunk-GNAQO3JX.js → chunk-GX2I7K4S.js} +19 -7
  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-HNAZBEDV.js → chunk-QRAFFI5V.js} +6 -4
  12. package/dist/chunks/chunk-R7ID2QVW.js +39 -0
  13. package/dist/chunks/chunk-SKYTL7AH.js +83 -0
  14. package/dist/chunks/{chunk-3UTSY2MH.js → chunk-TTT3KK46.js} +9 -12
  15. package/dist/chunks/{chunk-EWADWZYM.js → chunk-VDYO3QC7.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-JFJU4FGP.js +24 -0
  23. package/dist/chunks/orchestrator-KNCW4K57.js +32 -0
  24. package/dist/chunks/orchestrator-NIDJK4C3.js +25 -0
  25. package/dist/chunks/{session-UUHCIT66.js → session-CRFC3IEU.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-RBSOK3HT.js +378 -0
  29. package/dist/chunks/{telegram-X36RUESQ.js → telegram-JSGRYPIX.js} +24 -11
  30. package/dist/chunks/{wakeup-I7FQO5BS.js → wakeup-4IP4JXVF.js} +57 -16
  31. package/dist/index.js +62 -13
  32. package/package.json +4 -2
  33. package/dist/chunks/chunk-GVDXGKLD.js +0 -82
  34. package/dist/chunks/orchestrator-QCIY6FLH.js +0 -17
  35. package/dist/chunks/orchestrator-SDAA5TOH.js +0 -18
  36. package/dist/chunks/orchestrator-WXGJJEJW.js +0 -26
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
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.2 — 2026-11-19
6
+
7
+ ### Fixed
8
+ - Agent mode: some models described the change (or pasted the code) and asked "Would you like me to create the file?" instead of calling a tool, so nothing was staged. The instructions now say plainly to stage changes with the tools and never ask permission (approval happens afterwards). If a model still only describes the change, the agent tells it once to go ahead and stage it.
9
+
10
+ ## 0.2.1 — 2026-11-18
11
+
12
+ ### Changed
13
+ - **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.
14
+ - 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`.
15
+ - `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").
16
+ - `team invite <name>` for someone already on the team offers a new key instead of creating a duplicate member.
17
+
18
+
19
+
20
+ ### Added
21
+ - **Team mode** with the SaarthiClaw web dashboard: `saarthiclaw team connect | status | sync | suggest | invite | inbox | disconnect`, plus a 👥 Team entry in the main menu.
22
+ - Permission levels decide what happens after Agent / Plan / Ask `--save`:
23
+ - Admin and Trusted review and apply locally; the result is logged on the dashboard.
24
+ - Needs approval sends the changes to the Admin, and `team sync` applies the approved ones.
25
+ - Suggest only sends a suggestion instead.
26
+ - `team sync --wait` waits for the Admin's decision and applies as soon as it arrives.
27
+ - Approved changes are applied only if the file still matches the version the agent saw (SHA-256), so an approval never overwrites newer work.
28
+ - `doctor` reports the team connection; `init` mentions team mode.
29
+ - New audit event `submitted` (sent for approval; nothing written).
30
+
31
+ ### Changed
32
+ - Agent, Plan and Ask `--save` share one final review/apply step (`team/finalize.ts`); solo behaviour is unchanged.
33
+ - Telegram remote control is limited to the Admin and Trusted members when a project is in team mode.
34
+
5
35
  ## 0.1.0 — 2026-11-17
6
36
 
7
37
  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
 
@@ -0,0 +1,126 @@
1
+ import {
2
+ createAgentTools,
3
+ finalizeStaged,
4
+ finishOnLastStep,
5
+ generateWithProgress,
6
+ renderTerminalMarkdown
7
+ } from "./chunk-DSQDVSZS.js";
8
+ import {
9
+ ToolExecutor
10
+ } from "./chunk-OS5GVLKA.js";
11
+ import {
12
+ assertProjectOpen,
13
+ describeTeamMode,
14
+ getTeamContext
15
+ } from "./chunk-SKYTL7AH.js";
16
+ import {
17
+ RunCancelledError
18
+ } from "./chunk-HGBZ55ND.js";
19
+ import {
20
+ agentConfigFrom,
21
+ createTracker,
22
+ instructionsFor
23
+ } from "./chunk-GX2I7K4S.js";
24
+ import {
25
+ AI_MAX_RETRIES
26
+ } from "./chunk-BTFIQWAE.js";
27
+
28
+ // modes/agent/orchestrator.ts
29
+ import chalk from "chalk";
30
+ import { stepCountIs, ToolLoopAgent } from "ai";
31
+ async function runAgentMode(session, presetTask, modeOpts = {}) {
32
+ console.log(chalk.bold("\n🕵️ Agent Mode\n"));
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
+ }
55
+ const task = presetTask?.trim() || (await session.prompter.text({
56
+ message: "What should the agent do?",
57
+ placeholder: "A concrete task for this codebase…",
58
+ validate: (v) => v.trim() ? void 0 : "Please describe a task"
59
+ })).trim();
60
+ let allowShell = session.config.allowShellExecution;
61
+ if (!allowShell && !modeOpts.send) {
62
+ allowShell = await session.prompter.confirm({
63
+ message: "Allow shell commands in this session? (each command still needs your approval)",
64
+ initialValue: false
65
+ });
66
+ }
67
+ await runAgentTask(session, task, { allowShell, autoSend: modeOpts.send });
68
+ }
69
+ async function runAgentTask(session, task, opts) {
70
+ const team = await getTeamContext(session);
71
+ assertProjectOpen(team);
72
+ const tracker = createTracker(session, "agent");
73
+ const executor = new ToolExecutor(
74
+ tracker,
75
+ agentConfigFrom(session.config, { allowShellExecution: opts.allowShell })
76
+ );
77
+ const tools = createAgentTools(executor, { allowShell: opts.allowShell });
78
+ try {
79
+ const agent = new ToolLoopAgent({
80
+ model: session.model(),
81
+ instructions: instructionsFor(session, "agent", opts.allowShell),
82
+ tools,
83
+ stopWhen: stepCountIs(session.config.maxSteps.agent),
84
+ prepareStep: finishOnLastStep(session.config.maxSteps.agent),
85
+ maxOutputTokens: 4e3,
86
+ maxRetries: AI_MAX_RETRIES
87
+ });
88
+ let { text } = await generateWithProgress(agent, task, "Agent is thinking…");
89
+ if (tracker.PendingMutation().length === 0 && onlyDescribedTheChange(text)) {
90
+ console.log(chalk.dim("\nThe AI described the change instead of staging it; asking it to stage it now…"));
91
+ const followUp = await generateWithProgress(
92
+ agent,
93
+ [
94
+ { role: "user", content: task },
95
+ { role: "assistant", content: text },
96
+ { role: "user", content: "Yes, go ahead. Stage it now with the file tools (create_file / modify_file). Do not ask again; I will review the diff before anything is written." }
97
+ ],
98
+ "Staging the change…"
99
+ );
100
+ text = followUp.text || text;
101
+ }
102
+ if (text.trim()) console.log("\n" + renderTerminalMarkdown(text) + "\n");
103
+ const outcome = await finalizeStaged(session, tracker, executor, { task, summary: text, autoSend: opts.autoSend });
104
+ return { text, ...outcome };
105
+ } catch (e) {
106
+ const discarded = tracker.discardPending(e instanceof RunCancelledError ? "cancelled" : "aborted");
107
+ if (discarded > 0) {
108
+ console.log(chalk.yellow(`Discarded ${discarded} staged change${discarded === 1 ? "" : "s"} — nothing was written.`));
109
+ }
110
+ throw e;
111
+ } finally {
112
+ executor.clearStaging();
113
+ }
114
+ }
115
+ function onlyDescribedTheChange(text) {
116
+ const t = text.trim();
117
+ if (!t) return false;
118
+ if (/```|^ {4}\S/m.test(t)) return true;
119
+ return /(would you like|shall i|should i|do you want|want me to|let me know if you('d| would)? like|can i go ahead|proceed\?)/i.test(t);
120
+ }
121
+
122
+ export {
123
+ runAgentMode,
124
+ runAgentTask,
125
+ onlyDescribedTheChange
126
+ };
@@ -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,411 @@
1
+ import {
2
+ Activity,
3
+ composeBeforeAfter,
4
+ groupPending,
5
+ runApprovalFlow,
6
+ showGroup,
7
+ stagedSummaryTable
8
+ } from "./chunk-QRAFFI5V.js";
9
+ import {
10
+ getTeamContext
11
+ } from "./chunk-SKYTL7AH.js";
12
+ import {
13
+ sha256Hex
14
+ } from "./chunk-E4DRW4AW.js";
15
+ import {
16
+ RunCancelledError,
17
+ runCancellable
18
+ } from "./chunk-HGBZ55ND.js";
19
+ import {
20
+ resolveInsideRoot
21
+ } from "./chunk-XTVJWMUH.js";
22
+
23
+ // modes/agent/agent-tools.ts
24
+ import { tool } from "ai";
25
+ import { z } from "zod";
26
+ function createReadOnlyTools(executor) {
27
+ return {
28
+ read_file: tool({
29
+ description: "Read a text file from the workspace. Use a path relative to the project root. Secret files (.env, keys) are blocked.",
30
+ inputSchema: z.object({
31
+ path: z.string().describe("Relative file path, e.g. src/index.ts")
32
+ }),
33
+ execute: async ({ path: p }) => executor.readFile(p)
34
+ }),
35
+ list_files: tool({
36
+ description: "List files and directories under a path (relative to the project root).",
37
+ inputSchema: z.object({
38
+ path: z.string().default("."),
39
+ recursive: z.boolean().optional().default(false)
40
+ }),
41
+ execute: async ({ path: p, recursive }) => executor.listFiles(p, recursive ?? false)
42
+ }),
43
+ search_files: tool({
44
+ description: "Find files matching a glob pattern (e.g. '*.ts', 'src/**/*.md'). Optional content substring filter.",
45
+ inputSchema: z.object({
46
+ root: z.string().default(".").describe("Directory to search, relative to the project root"),
47
+ pattern: z.string().describe("Glob-like pattern using * and ** (forward slashes)"),
48
+ content_contains: z.string().optional()
49
+ }),
50
+ execute: async ({ root, pattern, content_contains }) => executor.searchFiles(root, pattern, content_contains)
51
+ }),
52
+ analyze_codebase: tool({
53
+ description: "Summarize structure: file counts, total size and most common extensions. Read-only.",
54
+ inputSchema: z.object({
55
+ path: z.string().default(".")
56
+ }),
57
+ execute: async ({ path: p }) => executor.analyzeCodebase(p)
58
+ }),
59
+ list_skills: tool({
60
+ description: "List absolute paths to SKILL.md files under configured skill directories.",
61
+ inputSchema: z.object({}),
62
+ execute: async () => executor.listSkills()
63
+ }),
64
+ read_skill: tool({
65
+ description: "Read a SKILL.md file returned by list_skills.",
66
+ inputSchema: z.object({
67
+ path: z.string()
68
+ }),
69
+ execute: async ({ path: p }) => executor.readSkill(p)
70
+ })
71
+ };
72
+ }
73
+ function createAgentTools(executor, options = {}) {
74
+ const base = {
75
+ ...createReadOnlyTools(executor),
76
+ create_file: tool({
77
+ description: "Stage creation of a new file (not written until the user approves).",
78
+ inputSchema: z.object({
79
+ path: z.string(),
80
+ content: z.string()
81
+ }),
82
+ execute: async ({ path: p, content }) => executor.createFile(p, content)
83
+ }),
84
+ modify_file: tool({
85
+ description: "Stage a full-file replacement for an existing file (pending approval). Provide the complete new contents.",
86
+ inputSchema: z.object({
87
+ path: z.string(),
88
+ content: z.string().describe("Complete new file contents")
89
+ }),
90
+ execute: async ({ path: p, content }) => executor.modifyFile(p, content)
91
+ }),
92
+ delete_file: tool({
93
+ description: "Stage deletion of a file (pending approval).",
94
+ inputSchema: z.object({
95
+ path: z.string()
96
+ }),
97
+ execute: async ({ path: p }) => executor.deleteFile(p)
98
+ }),
99
+ create_folder: tool({
100
+ description: "Stage creation of a directory tree (pending approval).",
101
+ inputSchema: z.object({
102
+ path: z.string().describe("Relative directory path")
103
+ }),
104
+ execute: async ({ path: p }) => executor.createFolder(p)
105
+ })
106
+ };
107
+ if (!options.allowShell) return base;
108
+ return {
109
+ ...base,
110
+ execute_shell: tool({
111
+ description: "Queue a shell command to run in the workspace root after the user approves it. Use only when necessary (e.g. installing a dependency, running tests).",
112
+ inputSchema: z.object({
113
+ command: z.string().describe("A single command line")
114
+ }),
115
+ execute: async ({ command }) => executor.queueShell(command)
116
+ })
117
+ };
118
+ }
119
+
120
+ // modes/agent/run.ts
121
+ import chalk from "chalk";
122
+ function preview(input, max = 140) {
123
+ let s;
124
+ try {
125
+ s = JSON.stringify(input) ?? "";
126
+ } catch {
127
+ s = String(input);
128
+ }
129
+ s = s.replace(/\s+/g, " ");
130
+ return s.length > max ? `${s.slice(0, max)}…` : s;
131
+ }
132
+ async function generateWithProgress(agent, prompt, label) {
133
+ const activity = new Activity();
134
+ activity.start(label);
135
+ try {
136
+ const result = await runCancellable(
137
+ (signal) => agent.generate({
138
+ ...typeof prompt === "string" ? { prompt } : { messages: prompt },
139
+ abortSignal: signal,
140
+ onStepFinish: (step) => {
141
+ const parts = step.content ?? [];
142
+ for (const part of parts) {
143
+ if (part.type === "tool-call") {
144
+ activity.log(`${chalk.green("✓")} ${chalk.bold(String(part.toolName))} ${chalk.dim(preview(part.input))}`);
145
+ } else if (part.type === "tool-error") {
146
+ const msg = part.error instanceof Error ? part.error.message : String(part.error);
147
+ activity.log(`${chalk.yellow("✗")} ${chalk.bold(String(part.toolName))} ${chalk.dim(preview(msg, 160))}`);
148
+ }
149
+ }
150
+ }
151
+ })
152
+ );
153
+ activity.stop(chalk.dim("Done thinking."));
154
+ return { text: result.text ?? "" };
155
+ } catch (e) {
156
+ activity.fail(e instanceof RunCancelledError ? "Cancelled." : "The AI run failed.");
157
+ throw e;
158
+ }
159
+ }
160
+ function reportApply(result) {
161
+ for (const s of result.shell) {
162
+ const head = s.ok ? chalk.green(`$ ${s.command}`) : chalk.red(`$ ${s.command} (exit ${s.exitCode ?? "?"})`);
163
+ console.log(`
164
+ ${head}`);
165
+ if (s.output) console.log(chalk.dim(s.output));
166
+ }
167
+ if (result.errors.length) {
168
+ console.log(chalk.red("\nSome operations reported errors:"));
169
+ for (const e of result.errors) console.log(chalk.red(` • ${e}`));
170
+ if (result.rolledBack) console.log(chalk.yellow(" File changes were rolled back; your files are unchanged."));
171
+ console.log("");
172
+ } else {
173
+ console.log(chalk.green(`
174
+ ✓ Applied ${result.applied} change${result.applied === 1 ? "" : "s"}.
175
+ `));
176
+ }
177
+ }
178
+
179
+ // modes/agent/loop-guards.ts
180
+ var READ_ONLY = /* @__PURE__ */ new Set(["read_file", "list_files", "search_files", "analyze_codebase", "list_skills", "read_skill"]);
181
+ var REPEAT_NOTE = "You already made this exact call and its result has not changed (see the earlier result). Do not repeat calls — use what you have and move on to your answer.";
182
+ function dedupeReadOnlyTools(tools) {
183
+ const seen = /* @__PURE__ */ new Set();
184
+ const out = {};
185
+ for (const [name, t] of Object.entries(tools)) {
186
+ const exec = t.execute;
187
+ if (!READ_ONLY.has(name) || !exec) {
188
+ out[name] = t;
189
+ continue;
190
+ }
191
+ out[name] = {
192
+ ...t,
193
+ execute: async (input, opts) => {
194
+ const key = `${name}:${JSON.stringify(input)}`;
195
+ if (seen.has(key)) return REPEAT_NOTE;
196
+ seen.add(key);
197
+ return exec(input, opts);
198
+ }
199
+ };
200
+ }
201
+ return out;
202
+ }
203
+ function finishOnLastStep(maxSteps) {
204
+ return ({ stepNumber }) => stepNumber >= maxSteps - 1 ? { toolChoice: "none", activeTools: [] } : {};
205
+ }
206
+
207
+ // tui/terminal-md.ts
208
+ import { marked } from "marked";
209
+ import { markedTerminal } from "marked-terminal";
210
+ var ready = false;
211
+ function ensureMarked() {
212
+ if (ready) return;
213
+ const width = Math.max(40, Math.min(process.stdout.columns || 80, 120));
214
+ marked.use(markedTerminal({ width, reflowText: true }));
215
+ ready = true;
216
+ }
217
+ function renderTerminalMarkdown(source) {
218
+ try {
219
+ ensureMarked();
220
+ return marked.parse(source.trimEnd(), { async: false }).trimEnd();
221
+ } catch {
222
+ return source;
223
+ }
224
+ }
225
+
226
+ // team/finalize.ts
227
+ import chalk2 from "chalk";
228
+
229
+ // team/payload.ts
230
+ import crypto from "node:crypto";
231
+ import fs from "node:fs";
232
+ function newBatchId() {
233
+ return `b_${crypto.randomBytes(8).toString("hex")}`;
234
+ }
235
+ function diskHash(root, rel) {
236
+ const abs = resolveInsideRoot(root, rel);
237
+ try {
238
+ const st = fs.statSync(abs);
239
+ if (!st.isFile()) return null;
240
+ return sha256Hex(fs.readFileSync(abs));
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+ function buildStagedItems(pending, root) {
246
+ const out = [];
247
+ for (const group of groupPending(pending, root)) {
248
+ const acts = pending.filter((a) => group.actionIds.includes(a.id)).sort((x, y) => x.timestamp.getTime() - y.timestamp.getTime());
249
+ if (group.kind === "shell") {
250
+ out.push({ group, actionIds: group.actionIds, item: { type: "shell_command", command: group.command ?? "", baseHash: null, risk: group.risk } });
251
+ continue;
252
+ }
253
+ if (group.kind === "folder") {
254
+ out.push({ group, actionIds: group.actionIds, item: { type: "folder_create", path: group.path, baseHash: null, risk: group.risk } });
255
+ continue;
256
+ }
257
+ const fileActs = acts.filter((a) => a.type !== "folder_create");
258
+ const baseHash = diskHash(root, group.path);
259
+ if (group.isDelete) {
260
+ if (baseHash === null) continue;
261
+ out.push({ group, actionIds: group.actionIds, item: { type: "file_delete", path: group.path, baseHash, diff: group.patch, risk: group.risk } });
262
+ continue;
263
+ }
264
+ const { after } = composeBeforeAfter(fileActs);
265
+ out.push({
266
+ group,
267
+ actionIds: group.actionIds,
268
+ item: { type: baseHash === null ? "file_create" : "file_modify", path: group.path, after, baseHash, diff: group.patch, risk: group.risk }
269
+ });
270
+ }
271
+ return out;
272
+ }
273
+ function describeItems(items) {
274
+ return items.map((s) => s.item.type === "shell_command" ? `run \`${s.item.command}\`` : `${s.item.type.replace("file_", "").replace("_create", " create")} ${s.item.path}`).join(", ");
275
+ }
276
+
277
+ // team/finalize.ts
278
+ function clip(s, n) {
279
+ const t = (s ?? "").trim();
280
+ return t.length > n ? `${t.slice(0, n - 1)}…` : t;
281
+ }
282
+ function wire(s, extra = {}) {
283
+ return { ...s.item, ...extra };
284
+ }
285
+ async function applyLocally(session, tracker, executor, info, team) {
286
+ const staged = team.client ? buildStagedItems(tracker.PendingMutation(), session.root) : [];
287
+ const ok = await runApprovalFlow(tracker, session.prompter, { root: session.root });
288
+ if (!ok) return { approved: false };
289
+ const result = executor.applyApprovedFromTracker();
290
+ reportApply(result);
291
+ if (team.client && !team.offline && staged.length) {
292
+ const byId = new Map(tracker.getActions().map((a) => [a.id, a]));
293
+ const decided = staged.map((s) => ({ s, statuses: s.actionIds.map((id) => byId.get(id)?.status) })).filter(({ statuses }) => statuses.some((st) => st === "applied" || st === "failed"));
294
+ if (decided.length) {
295
+ const items = decided.map(({ s, statuses }) => {
296
+ const good = statuses.every((st) => st === "applied");
297
+ const why = s.actionIds.map((id) => byId.get(id)?.details.error).find(Boolean);
298
+ return wire(s, { after: void 0, ok: good, message: good ? "Applied" : clip(why ?? "Failed", 300) });
299
+ });
300
+ try {
301
+ await team.client.recordApplied({ task: clip(info.task, 1e3), summary: clip(info.summary, 1500), batchId: newBatchId(), items });
302
+ console.log(chalk2.dim(`📋 Logged ${items.length} change${items.length === 1 ? "" : "s"} on the team dashboard.
303
+ `));
304
+ } catch (e) {
305
+ console.log(chalk2.yellow(`⚠ Applied locally, but could not log on the team dashboard: ${e.message}
306
+ `));
307
+ }
308
+ }
309
+ }
310
+ return { approved: true, result };
311
+ }
312
+ async function sendForApproval(session, tracker, info, team) {
313
+ const pending = tracker.PendingMutation();
314
+ const staged = buildStagedItems(pending, session.root);
315
+ if (staged.length === 0) {
316
+ tracker.discardPending("nothing to send");
317
+ console.log(chalk2.dim("\nNothing to send.\n"));
318
+ return { approved: false };
319
+ }
320
+ console.log(chalk2.bold(`
321
+ 📝 Staged changes (${staged.length}) — nothing has been written`));
322
+ console.log(chalk2.dim(` Your level is Needs approval: these go to the Admin, who approves or rejects each one.
323
+ `));
324
+ console.log(stagedSummaryTable(pending, session.root));
325
+ for (const s of staged) showGroup(s.group);
326
+ console.log("");
327
+ const how = info.autoSend ? "all" : await session.prompter.select({
328
+ message: `Send ${staged.length === 1 ? "this change" : `these ${staged.length} changes`} to the Admin for approval?`,
329
+ options: [
330
+ { value: "all", label: "Send all for approval" },
331
+ ...staged.length > 1 ? [{ value: "pick", label: "Choose which to send" }] : [],
332
+ { value: "none", label: "Discard (send nothing)" }
333
+ ],
334
+ initialValue: "all"
335
+ });
336
+ let chosen = staged;
337
+ if (how === "none") chosen = [];
338
+ if (how === "pick") {
339
+ const ids = await session.prompter.multiselect({
340
+ message: "Which changes should go to the Admin?",
341
+ options: staged.map((s, i) => ({ value: String(i), label: s.group.label })),
342
+ initialValues: staged.map((_, i) => String(i)),
343
+ required: false
344
+ });
345
+ chosen = staged.filter((_, i) => ids.includes(String(i)));
346
+ }
347
+ if (chosen.length === 0) {
348
+ tracker.discardPending("not sent");
349
+ console.log(chalk2.yellow("\nNothing was sent and nothing was written.\n"));
350
+ return { approved: false, sent: 0 };
351
+ }
352
+ const res = await team.client.propose({
353
+ task: clip(info.task, 1e3),
354
+ summary: clip(info.summary, 1500),
355
+ batchId: newBatchId(),
356
+ items: chosen.map((s) => wire(s))
357
+ });
358
+ for (const s of chosen) for (const id of s.actionIds) tracker.updateStatus(id, "submitted", false);
359
+ tracker.discardPending("not sent");
360
+ console.log(chalk2.green(`
361
+ 📨 Sent ${res.ids.length} change${res.ids.length === 1 ? "" : "s"} to the Admin for approval.`) + chalk2.dim(" Nothing was written yet.\n"));
362
+ const wait = session.prompter.interactive ? await session.prompter.confirm({ message: "Wait here for the Admin's decision? (approved changes are applied here right after)", initialValue: true }) : false;
363
+ if (wait) {
364
+ const { runTeamSync } = await import("./sync-S2A65FIE.js");
365
+ const summary = await runTeamSync(session, { wait: true });
366
+ return { approved: summary.applied > 0, sent: res.ids.length };
367
+ }
368
+ console.log(chalk2.dim(" When the Admin approves on the dashboard, run ") + chalk2.bold("saarthiclaw team sync") + chalk2.dim(" to apply them here"));
369
+ console.log(chalk2.dim(" (or ") + chalk2.bold("saarthiclaw team sync --wait") + chalk2.dim(" to wait for the decision).\n"));
370
+ return { approved: false, sent: res.ids.length };
371
+ }
372
+ async function offerSuggestion(session, tracker, info, team) {
373
+ const staged = buildStagedItems(tracker.PendingMutation(), session.root);
374
+ tracker.discardPending("suggest-only level");
375
+ console.log(chalk2.yellow("\nYour level is Suggest only, so code changes can't be applied or sent for approval. Nothing was written."));
376
+ const send = await session.prompter.confirm({ message: "Send this as a suggestion to the Admin instead?", initialValue: true });
377
+ if (!send) return { approved: false };
378
+ const touched = staged.length ? ` (the agent wanted to ${clip(describeItems(staged), 200)})` : "";
379
+ const message = clip(`${info.task}${touched}`, 500).padEnd(10, ".");
380
+ await team.client.suggest(message);
381
+ console.log(chalk2.green("\n💡 Suggestion sent. The Admin sees it on the dashboard under Suggestions.\n"));
382
+ return { approved: false };
383
+ }
384
+ async function finalizeStaged(session, tracker, executor, info) {
385
+ if (tracker.PendingMutation().length === 0) {
386
+ console.log(chalk2.dim("\nNothing to approve — no file changes were staged.\n"));
387
+ return { approved: false };
388
+ }
389
+ const team = await getTeamContext(session);
390
+ switch (team.mode) {
391
+ case "solo":
392
+ case "admin":
393
+ case "trusted":
394
+ return applyLocally(session, tracker, executor, info, team);
395
+ case "needs_approval":
396
+ return sendForApproval(session, tracker, info, team);
397
+ case "suggest_only":
398
+ return offerSuggestion(session, tracker, info, team);
399
+ }
400
+ }
401
+
402
+ export {
403
+ createReadOnlyTools,
404
+ createAgentTools,
405
+ generateWithProgress,
406
+ REPEAT_NOTE,
407
+ dedupeReadOnlyTools,
408
+ finishOnLastStep,
409
+ renderTerminalMarkdown,
410
+ finalizeStaged
411
+ };