aegis-desktop 1.0.13 → 1.0.15

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 (96) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/bin/aegis.js +1 -32
  3. package/lib/account-key.js +1 -56
  4. package/lib/auto.js +1 -430
  5. package/lib/avatar/companion.js +1 -698
  6. package/lib/avatar/cosmetics.js +1 -532
  7. package/lib/avatar/events.js +1 -344
  8. package/lib/avatar/holder-turn.js +1 -350
  9. package/lib/avatar/holders.js +1 -612
  10. package/lib/avatar/identity.js +1 -641
  11. package/lib/avatar/level.js +1 -368
  12. package/lib/avatar/mirror.js +1 -524
  13. package/lib/avatar/persona.js +1 -388
  14. package/lib/avatar/profile.js +1 -977
  15. package/lib/avatar/register.js +1 -307
  16. package/lib/avatar/store.js +1 -472
  17. package/lib/avatar/tiers.js +1 -38
  18. package/lib/avatar/transfer.js +1 -415
  19. package/lib/avatar/turn.js +1 -216
  20. package/lib/avatar/voice.js +1 -328
  21. package/lib/avatar/xp.js +1 -404
  22. package/lib/deep-link.js +1 -120
  23. package/lib/fingerprint.js +2 -347
  24. package/lib/google-connect.js +1 -169
  25. package/lib/local/agents.js +1 -105
  26. package/lib/local/autonomous.js +1 -1045
  27. package/lib/local/claude-pro.js +1 -993
  28. package/lib/local/context.js +1 -95
  29. package/lib/local/engine.js +1 -3228
  30. package/lib/local/entitlement.js +1 -654
  31. package/lib/local/git-scope.js +1 -228
  32. package/lib/local/local.js +1 -2135
  33. package/lib/local/prompt.js +1 -275
  34. package/lib/local/queue.js +1 -560
  35. package/lib/local/session-rounds.js +1 -208
  36. package/lib/local/shell.js +1 -680
  37. package/lib/local/telemetry.js +1 -470
  38. package/lib/local/tools.js +1 -1238
  39. package/lib/local/turn-guard.js +1 -300
  40. package/lib/local/worktree-lock.js +1 -235
  41. package/lib/provider-key-mirror.js +1 -252
  42. package/lib/quick-launcher.js +1 -84
  43. package/lib/settings.js +1 -890
  44. package/lib/sync/memory-queue.js +1 -60
  45. package/lib/sync/persist-gate.js +1 -148
  46. package/lib/sync/sessions.js +1 -106
  47. package/lib/window-state.js +1 -66
  48. package/main.js +3 -4390
  49. package/package.json +3 -5
  50. package/preload.js +3 -628
  51. package/renderer/app.js +1 -6560
  52. package/renderer/avatar/assemble.js +1 -335
  53. package/renderer/avatar/avatar.js +1 -380
  54. package/renderer/avatar/cards.js +1 -141
  55. package/renderer/avatar/hud.js +1 -206
  56. package/renderer/avatar/machine.js +1 -213
  57. package/renderer/avatar/pane.js +1 -439
  58. package/renderer/avatar/parts.js +1 -437
  59. package/renderer/budget.js +1 -168
  60. package/renderer/companion.js +1 -223
  61. package/renderer/diff.js +1 -359
  62. package/renderer/diffview.js +1 -336
  63. package/renderer/fingerprint.js +3 -720
  64. package/renderer/markdown.js +1 -168
  65. package/renderer/provider-toolbar.js +1 -134
  66. package/renderer/providers.js +1 -259
  67. package/renderer/quick.js +1 -191
  68. package/renderer/stream-policy.js +1 -306
  69. package/renderer/transcript-view.js +1 -323
  70. package/renderer/usage.js +1 -1239
  71. package/vendor/aegis.js +1 -2054
  72. package/vendor/attest.js +1 -442
  73. package/vendor/authorship-key.js +1 -410
  74. package/vendor/auto-provision.js +1 -134
  75. package/vendor/brain-catalog.js +1 -268
  76. package/vendor/byok-catalog.js +1 -230
  77. package/vendor/credentials.js +1 -494
  78. package/vendor/device-fingerprint.js +1 -141
  79. package/vendor/drive-connect.js +1 -85
  80. package/vendor/drive-upload.js +1 -174
  81. package/vendor/env-file.js +1 -1273
  82. package/vendor/fingerprint.js +1 -1064
  83. package/vendor/foreign-memory.js +1 -669
  84. package/vendor/google-signin.js +1 -125
  85. package/vendor/hooks.js +1 -430
  86. package/vendor/model-discovery.js +1 -330
  87. package/vendor/platform.js +1 -937
  88. package/vendor/prefs.js +1 -351
  89. package/vendor/presence-constants.js +1 -107
  90. package/vendor/presence.js +1 -438
  91. package/vendor/record-vault.js +3 -1055
  92. package/vendor/session-store.js +1 -548
  93. package/vendor/topup.js +1 -297
  94. package/vendor/touch.js +1 -458
  95. package/vendor/update.js +1 -704
  96. package/vendor/user-models.js +1 -381
@@ -1,1240 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * tools.js — the local tool layer for the desktop agent loop (client half of
10
- * the upstream engine's tool calling).
11
- *
12
- * Two jobs, mirroring the upstream engine reference:
13
- * 1. Tool schemas in the wire format each API family expects — Anthropic's
14
- * `{name, description, input_schema}` vs OpenAI-compatible
15
- * `{type:'function', function:{name, description, parameters}}`.
16
- * 2. Local execution of the builtin tools (readFile, writeFile, editFile,
17
- * listDir, glob, grep, exec), so a chat turn in the desktop app can
18
- * actually touch the machine instead of only talking about it.
19
- *
20
- * `exec` runs in a persistent shell session (shell.js) when the caller
21
- * supplies `ctx.getShell` — cd/export/env state then carries across calls
22
- * within one turn, same as the CLI's Bash tool. `task` is advertised here
23
- * (SUBAGENT_TOOL) but has no local executor: it needs to run the model, so
24
- * engine.js's chat loop handles it directly as a nested subagent turn.
25
- *
26
- * Path note: this lives under desktop/lib/local/ (not desktop/lib/) because
27
- * the CI thin-shell guard (.github/workflows/ci.yml, step 4) allowlists only
28
- * `desktop/lib/local/`, `desktop/lib/sync/` and `desktop/lib/settings.js` as
29
- * transport paths — a new file directly under desktop/lib/ fails that guard.
30
- *
31
- * Everything here is self-contained (node:child_process + node:fs + node:path
32
- * only, no new dependencies) and NEVER throws: each executor resolves either
33
- * `{ ok: true, output }` or `{ ok: false, error }`, so a bad path, a dead
34
- * command or a hostile arg string can only ever become a tool error handed
35
- * back to the model — never a rejected IPC call or a crashed main process.
36
- *
37
- * SECURITY: this is a deliberate widening of the app's sandbox. The renderer
38
- * stays contextIsolated + sandboxed with no fs/child_process of its own; the
39
- * executor lives in the MAIN process and is reachable from the renderer only
40
- * through the whitelisted `tools:` IPC surface (see main.js/preload.js and
41
- * docs/desktop-tools.md). There is no path jail: the tools deliberately run
42
- * with the user's own privileges, exactly like the CLI does. Treat any future
43
- * renderer-side input that reaches these args as privileged.
44
- */
45
-
46
- const { spawn } = require('node:child_process');
47
- const crypto = require('node:crypto');
48
- const fs = require('node:fs');
49
- const path = require('node:path');
50
- const { pathToFileURL } = require('node:url');
51
- const { agentRoles } = require('./agents.js');
52
-
53
- // The ONE platform module (client/platform.js, Phase 30.1). This file used to
54
- // carry a private `shellSpec()` that read `process.platform` directly, which
55
- // meant the Windows half of the decision could only ever be exercised on a
56
- // Windows host — and this project has no Windows runner. Resolved the same two
57
- // ways this repo resolves every shared module (see engine.js): repo-relative in
58
- // a checkout and in the CLI's mirrored vendor tree, then the staged app-dir
59
- // copy a packaged desktop build carries. A missing copy would leave `exec` with
60
- // no shell at all, so the failure is loud here rather than lazily deferred: the
61
- // fallback loads or this module does not.
62
- let platform;
63
- try {
64
- platform = require('../../../client/platform.js');
65
- } catch (err) {
66
- try {
67
- platform = require('../../vendor/platform.js');
68
- } catch {
69
- throw new Error(
70
- `tools.js: cannot load the shared platform module (client/platform.js, ` +
71
- `or its staged copy): ${err && err.message ? err.message : err}`
72
- );
73
- }
74
- }
75
-
76
- const OUTPUT_CAP = 30_000; // chars fed back to the model per tool result
77
-
78
- /**
79
- * What every path argument accepts, stated ONCE so the ten schemas below cannot
80
- * drift from each other or from what normalizeArgs actually does.
81
- *
82
- * It names the platform requirement explicitly because the failure it prevents
83
- * was a model guessing posix on a Windows host (see client/platform.js
84
- * resolvePath): `/home/you/Desktop/x.txt` there is drive-relative, so the write
85
- * SUCCEEDED at `C:\home\you\Desktop\x.txt` and the user found nothing on their
86
- * Desktop. The schema is the first place to say so — a refusal after the fact
87
- * costs the model a round, a correct description costs it nothing.
88
- */
89
- // Kept SHORT on purpose. This sentence is repeated in the description of every
90
- // path argument (9 of the 10 tools), so its length is paid once per tool, every
91
- // round, and the tool schemas are part of the wire prefix the provider is asked
92
- // to cache. The long form spelled out win32 examples and the Environment-block
93
- // cross-reference — 267 chars, ~68 tokens, ~616 tokens per round once
94
- // multiplied across the nine. That instruction is NOT lost: prompt.js's
95
- // TOOL_LINE states the same rule once, in the system prompt where it belongs
96
- // and where it costs one copy instead of nine. `test/tool-paths.test.mjs`
97
- // asserts this constant appears in each path argument, so it must stay the
98
- // single shared string rather than being inlined per tool.
99
- const PATH_ARG_DESC =
100
- 'Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.';
101
-
102
- /** `<what>. <the path rules>` — the shape every path argument's description takes. */
103
- const pathDesc = (what) => `${what}. ${PATH_ARG_DESC}`;
104
-
105
- // The dialect probe (Phase 30.3), from the same module the session lives in: a
106
- // one-shot `exec` must run the command in a shell that was PROBED to speak the
107
- // dialect the command is written in, never in an unprobed `$SHELL`. Lives next
108
- // to this file in every tree that has it (repo, CLI vendor, packaged app dir).
109
- const shells = require('./shell.js');
110
- const READ_LINE_CAP = 2000; // default line limit for readFile
111
- const MATCH_CAP = 100; // max glob/grep hits per call
112
- // readFileSync loads the whole file before `limit` ever truncates — refuse
113
- // oversized reads outright instead of freezing the turn on a multi-GB log.
114
- const READ_SIZE_CAP = 25 * 1024 * 1024;
115
- const GREP_SIZE_CAP = 10 * 1024 * 1024; // grep silently skips files above this
116
- const EXEC_TIMEOUT_DEFAULT = 120_000;
117
- const EXEC_TIMEOUT_CAP = 600_000; // 10 minutes, matches the CLI's cap
118
- const EXEC_MAX_BUFFER = 1_048_576; // 1 MB of combined stdout+stderr
119
- // The LCS diff below is O(lines_before * lines_after); past this many cells
120
- // (or this many lines on either side) the diff is skipped in favor of a
121
- // one-line summary rather than freezing the approval flow on a huge file.
122
- const DIFF_MAX_CELLS = 4_000_000;
123
- const DIFF_MAX_LINES = 20_000;
124
-
125
- /** Truncate oversized tool output (the model never needs the whole log). */
126
- function cap(s) {
127
- const text = String(s == null ? '' : s);
128
- return text.length > OUTPUT_CAP
129
- ? `${text.slice(0, OUTPUT_CAP)}\n… (truncated)`
130
- : text;
131
- }
132
-
133
- const ok = (output) => ({ ok: true, output: cap(output) });
134
- const fail = (error) => ({ ok: false, error: cap(error) });
135
-
136
- // ── Schemas ─────────────────────────────────────────────────────────────────
137
-
138
- /**
139
- * Canonical descriptions + parameters, in one place per tool. The two wire
140
- * formats below are pure projections of this map, so a schema can never drift
141
- * between providers (see the conversion test in test/local-tools.test.mjs).
142
- */
143
- const SCHEMAS = {
144
- readFile: {
145
- name: 'readFile',
146
- description: 'Read a file. Returns line-numbered content.',
147
- parameters: {
148
- type: 'object',
149
- properties: {
150
- file_path: { type: 'string', description: pathDesc('The file to read') },
151
- offset: { type: 'number', description: 'Start line (0-based)' },
152
- limit: { type: 'number', description: `The number of lines to read (max 10000, default ${READ_LINE_CAP})` },
153
- },
154
- required: ['file_path'],
155
- additionalProperties: false,
156
- },
157
- },
158
- writeFile: {
159
- name: 'writeFile',
160
- description:
161
- 'Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.',
162
- parameters: {
163
- type: 'object',
164
- properties: {
165
- file_path: { type: 'string', description: pathDesc('The file to write') },
166
- content: { type: 'string', description: 'Full file contents' },
167
- },
168
- required: ['file_path', 'content'],
169
- additionalProperties: false,
170
- },
171
- },
172
- editFile: {
173
- name: 'editFile',
174
- description:
175
- 'Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a ' +
176
- 'missing or ambiguous match rather than guessing.',
177
- parameters: {
178
- type: 'object',
179
- properties: {
180
- file_path: { type: 'string', description: pathDesc('The file to edit') },
181
- old_string: { type: 'string', description: 'Text to replace; must be unique unless replace_all' },
182
- new_string: { type: 'string', description: 'Replacement text' },
183
- replace_all: { type: 'boolean', description: 'Replace every occurrence' },
184
- },
185
- required: ['file_path', 'old_string', 'new_string'],
186
- additionalProperties: false,
187
- },
188
- },
189
- listDir: {
190
- name: 'listDir',
191
- description: 'List one directory (non-recursive). Skips node_modules, .git, dist.',
192
- parameters: {
193
- type: 'object',
194
- properties: {
195
- path: { type: 'string', description: pathDesc('The directory to list (default: the working directory)') },
196
- },
197
- required: [],
198
- additionalProperties: false,
199
- },
200
- },
201
- glob: {
202
- name: 'glob',
203
- description:
204
- 'Find files by glob (**, *, ?). Skips node_modules, .git, dist.',
205
- parameters: {
206
- type: 'object',
207
- properties: {
208
- pattern: { type: 'string', description: 'Glob, e.g. "**/*.test.js"' },
209
- path: { type: 'string', description: pathDesc('Search root (default: the working directory)') },
210
- },
211
- required: ['pattern'],
212
- additionalProperties: false,
213
- },
214
- },
215
- grep: {
216
- name: 'grep',
217
- description: 'Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.',
218
- parameters: {
219
- type: 'object',
220
- properties: {
221
- pattern: { type: 'string', description: 'The regular expression to search for' },
222
- path: { type: 'string', description: pathDesc('The directory to search in (default: the working directory)') },
223
- },
224
- required: ['pattern'],
225
- additionalProperties: false,
226
- },
227
- },
228
- exec: {
229
- name: 'exec',
230
- description:
231
- 'Run a shell command in a PERSISTENT session: cd and exported env carry across calls in ' +
232
- 'this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.',
233
- parameters: {
234
- type: 'object',
235
- properties: {
236
- command: { type: 'string', description: 'Command to run' },
237
- cwd: { type: 'string', description: pathDesc('Run this one command elsewhere; session cwd unchanged') },
238
- timeout: { type: 'number', description: `Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})` },
239
- description: { type: 'string', description: 'A brief description of what the command does (for display)' },
240
- },
241
- required: ['command'],
242
- additionalProperties: false,
243
- },
244
- },
245
- hooks: {
246
- name: 'hooks',
247
- description:
248
- 'Hook status for this machine, from the same shared implementation the CLI\'s /hooks uses: ' +
249
- 'the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) ' +
250
- 'and whether this repo\'s .githooks/ guard hooks are actually installed (core.hooksPath). ' +
251
- 'Read-only. Use installHooks to install them.',
252
- parameters: {
253
- type: 'object',
254
- properties: {
255
- sub: { type: 'string', enum: ['status', 'list'], description: 'status (default) or the full config listing' },
256
- cwd: { type: 'string', description: pathDesc('Repo to inspect (default: the working directory)') },
257
- },
258
- required: [],
259
- additionalProperties: false,
260
- },
261
- },
262
- installHooks: {
263
- name: 'installHooks',
264
- description:
265
- 'Install this repo\'s guard hooks: point git\'s core.hooksPath at .githooks/ (the agent-key ' +
266
- 'gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified ' +
267
- 'by reading the config back. Pass dry_run to see the exact commands without running them. ' +
268
- 'Without this, a fresh clone runs NO guard hooks.',
269
- parameters: {
270
- type: 'object',
271
- properties: {
272
- cwd: { type: 'string', description: pathDesc('Repo to install into (default: the working directory)') },
273
- dry_run: { type: 'boolean', description: 'Print the commands instead of running them' },
274
- },
275
- required: [],
276
- additionalProperties: false,
277
- },
278
- },
279
- task: {
280
- name: 'task',
281
- description:
282
- 'Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a ' +
283
- 'final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.',
284
- parameters: {
285
- type: 'object',
286
- properties: {
287
- description: { type: 'string', description: 'Short label (3-5 words)' },
288
- subagent_type: {
289
- type: 'string',
290
- enum: [...agentRoles(), 'general'],
291
- description: 'Which specialist preset to spawn (general = a capable all-purpose agent)',
292
- },
293
- prompt: { type: 'string', description: 'The full, self-contained task instructions for the subagent' },
294
- },
295
- required: ['description', 'prompt'],
296
- additionalProperties: false,
297
- },
298
- },
299
- };
300
-
301
- // task is executed by the chat loop (it needs to run the model), not by the
302
- // local executors below — advertised in the schemas but handled in
303
- // engine.js's chat(). Subagents get task too, so delegation can nest —
304
- // engine.js drops it (via includeSubagent) once the delegation chain passes
305
- // MAX_SUBAGENT_DEPTH, hard-bounding runaway recursion.
306
- const SUBAGENT_TOOL = 'task';
307
-
308
- /**
309
- * The hook layer (`hooks`, `installHooks`) is the ONE part of this registry that
310
- * is not agent work, and it is the one part the benchmark never touches.
311
- *
312
- * Measured on `benchmarks/raw/beat-pi-20261022-2318` (three tasks, the same wire
313
- * model, nine trials): the advertised schemas are re-sent as a wire PREFIX on
314
- * every round, and these two are 427 of its ~1,757 tokens. On the round that
315
- * misses the prefix cache they are billed at the miss rate; on every later round
316
- * they are billed at the cheap hit rate but are still tokens the model reads
317
- * before it reads the task. Pi ships seven tools and no hook surface at all.
318
- *
319
- * So they stay RUNNABLE (`isTool`, `executeTool`, `toolList`, the CLI's `/hooks`)
320
- * and stay on the schema list for a caller that asks for them, but they are no
321
- * longer advertised to the model by default. Capability is unchanged; the
322
- * prefix it was paying for is gone.
323
- */
324
- const HOOK_TOOLS = new Set(['hooks', 'installHooks']);
325
-
326
- /** Tool names in advertisement order. `includeSubagent: false` drops task (depth cap). */
327
- function toolNames({ includeSubagent = true, includeHooks = false } = {}) {
328
- return schemaList({ includeSubagent, includeHooks }).map((s) => s.name);
329
- }
330
-
331
- function schemaList({ includeSubagent = true, includeHooks = false } = {}) {
332
- return Object.values(SCHEMAS).filter(
333
- (s) =>
334
- (includeSubagent || s.name !== SUBAGENT_TOOL) &&
335
- (includeHooks || !HOOK_TOOLS.has(s.name))
336
- );
337
- }
338
-
339
- /**
340
- * OpenAI-compatible /chat/completions tool definitions ({type:'function', function}).
341
- * `includeHooks: true` re-advertises the hook tools; the default is the agent
342
- * set, because a hook install is a thing the USER asks the CLI for, not a step
343
- * in a coding task.
344
- */
345
- function openaiTools({ includeSubagent = true, includeHooks = false } = {}) {
346
- return schemaList({ includeSubagent, includeHooks }).map((s) => ({
347
- type: 'function',
348
- function: { name: s.name, description: s.description, parameters: s.parameters },
349
- }));
350
- }
351
-
352
- /**
353
- * The advertised tool list. There is exactly ONE wire format now — every turn
354
- * goes through the AEGIS relay, which speaks the OpenAI shape — so this takes
355
- * no `wire` argument. The Anthropic-shaped variant went away with the
356
- * direct-dial transport. `includeSubagent: false` drops the task tool
357
- * (subagent depth cap); `includeHooks: true` re-adds hooks/installHooks.
358
- */
359
- function toolsFor({ includeSubagent = true, includeHooks = false } = {}) {
360
- return openaiTools({ includeSubagent, includeHooks });
361
- }
362
-
363
- // ── Path normalisation ──────────────────────────────────────────────────────
364
-
365
- /**
366
- * Which argument of each tool is a path on this machine. `task` has none (its
367
- * argument is a prompt), and `exec`'s `command` is deliberately absent: a shell
368
- * command is not a path and its contents are the shell's business, not ours.
369
- */
370
- const TOOL_PATH_ARGS = Object.freeze({
371
- readFile: ['file_path'],
372
- writeFile: ['file_path'],
373
- editFile: ['file_path'],
374
- listDir: ['path'],
375
- glob: ['path'],
376
- grep: ['path'],
377
- exec: ['cwd'],
378
- hooks: ['cwd'],
379
- installHooks: ['cwd'],
380
- });
381
-
382
- /**
383
- * Resolve every path argument of one tool call against THIS machine, returning
384
- * `{ ok, args, error }` — `args` is a copy with each path replaced by its real
385
- * absolute form, and a single refusal fails the whole call.
386
- *
387
- * Three reasons this is one function applied to the call, rather than a
388
- * `resolvePath` sprinkled through each executor:
389
- *
390
- * 1. The GUARDS read the path too. tools/agent-gate.mjs does
391
- * `path.resolve(cwd, args.file_path)` to decide whether the target sits in
392
- * an agent-gated tree, and engine.js's covenant check inspects `args`
393
- * before anything runs. A `~/…` reaching them unexpanded means they rule on
394
- * `<cwd>/~/…` — a different file than the one that would be written. The
395
- * only way the guard and the write can agree is for the path to be real
396
- * BEFORE either looks at it.
397
- * 2. The approval gate shows a diff for one path and then writes to another
398
- * otherwise: previewMutation and applyChecked must resolve identically, and
399
- * sharing this function is what makes that true by construction.
400
- * 3. An absent or empty argument is left ALONE, so each executor keeps its own
401
- * "required" error and its own default (listDir with no `path` still means
402
- * the working directory). Normalising only what was actually supplied is
403
- * what keeps this a path fix and not a behaviour change.
404
- *
405
- * Idempotent, because resolvePath is: engine.js normalises early for the guards
406
- * and executeTool normalises again for a direct caller, and the second pass is a
407
- * no-op rather than a second resolution.
408
- */
409
- function normalizeArgs(name, args, ctx = {}) {
410
- const input = args && typeof args === 'object' ? args : {};
411
- const keys = TOOL_PATH_ARGS[name];
412
- if (!keys) return { ok: true, args: input, error: null };
413
-
414
- let out = input;
415
- for (const key of keys) {
416
- const value = input[key];
417
- if (typeof value !== 'string' || !value.trim()) continue; // absent → the executor's default
418
- const res = platform.resolvePath(value, {
419
- // The tool layer's platform seam, the same one `client/platform.js`
420
- // takes on every function and `shell.js` already passes at its call
421
- // site: `ctx.platform` names the host whose path rules apply. Absent
422
- // (every existing caller), `resolvePath` falls back to
423
- // `process.platform`, so this changes nothing at runtime — but it is
424
- // what lets the win32 and darwin branches of THIS layer be exercised
425
- // from a Linux CI, instead of being reachable only on a foreign host.
426
- // See test/platform-parity.test.mjs.
427
- platform: ctx && ctx.platform ? ctx.platform : undefined,
428
- cwd: ctx && ctx.cwd ? ctx.cwd : undefined,
429
- desktopdir: ctx && ctx.desktopdir ? ctx.desktopdir : undefined,
430
- });
431
- if (!res.ok) return { ok: false, args: input, error: `${name}: ${key} — ${res.error}` };
432
- if (res.path !== value) {
433
- if (out === input) out = { ...input };
434
- out[key] = res.path;
435
- }
436
- }
437
- return { ok: true, args: out, error: null };
438
- }
439
-
440
- /**
441
- * The directory a tool with no explicit `path` works in: this TURN's working
442
- * directory, not the host process's.
443
- *
444
- * `process.cwd()` is wrong here and was visibly wrong off Linux: the Electron
445
- * main process inherits whatever the OS launched the app from — `/` from a .desktop
446
- * entry, `C:\Program Files\AEGIS Desktop` from a Windows shortcut — so a bare
447
- * `listDir`/`glob`/`grep` searched the install directory instead of the user's
448
- * repo. It stays the fallback for a direct call that supplies no ctx.
449
- */
450
- function baseDir(ctx) {
451
- return (ctx && typeof ctx.cwd === 'string' && ctx.cwd) || process.cwd();
452
- }
453
-
454
- // ── Executors ───────────────────────────────────────────────────────────────
455
-
456
- function readFile({ file_path, offset = 0, limit } = {}) {
457
- try {
458
- if (!file_path) return fail('file_path is required');
459
- const stat = fs.statSync(file_path);
460
- if (stat.isDirectory()) return fail(`${file_path} is a directory (use listDir)`);
461
- if (stat.size > READ_SIZE_CAP) {
462
- const mb = (stat.size / 1048576).toFixed(1);
463
- return fail(
464
- `${file_path} is ${mb} MB — too large to read (limit ${READ_SIZE_CAP / 1048576} MB). ` +
465
- 'Use exec with grep/head to inspect it instead.'
466
- );
467
- }
468
- const lines = fs.readFileSync(file_path, 'utf8').split('\n');
469
- const start = Math.max(0, Number(offset) || 0);
470
- const count = Math.max(1, Math.min(Number(limit) || READ_LINE_CAP, 10_000));
471
- const picked = lines.slice(start, start + count);
472
- const numbered = picked.map((l, i) => `${i + start + 1}| ${l}`).join('\n');
473
- const tail =
474
- start + picked.length < lines.length
475
- ? `\n… (${lines.length - start - picked.length} more lines)`
476
- : '';
477
- return ok(numbered + tail);
478
- } catch (e) {
479
- return fail(e && e.message ? e.message : String(e));
480
- }
481
- }
482
-
483
- function writeFile({ file_path, content } = {}) {
484
- try {
485
- if (!file_path) return fail('file_path is required');
486
- fs.mkdirSync(path.dirname(file_path), { recursive: true });
487
- fs.writeFileSync(file_path, String(content == null ? '' : content), 'utf8');
488
- return ok(`Wrote ${String(content == null ? '' : content).length} bytes to ${file_path}`);
489
- } catch (e) {
490
- return fail(e && e.message ? e.message : String(e));
491
- }
492
- }
493
-
494
- function editFile(args = {}) {
495
- try {
496
- const preview = previewEditFile(args);
497
- if (!preview.ok) return fail(preview.error);
498
- fs.writeFileSync(args.file_path, preview.after, 'utf8');
499
- return ok(`Edited ${args.file_path} (${preview.count} occurrence${preview.count > 1 ? 's' : ''} replaced)`);
500
- } catch (e) {
501
- return fail(e && e.message ? e.message : String(e));
502
- }
503
- }
504
-
505
- // ── Approval-gate helpers ───────────────────────────────────────────────────
506
- //
507
- // The renderer approval gate (desktop/lib/local/engine.js gatedExecuteTool)
508
- // needs to show the user a diff BEFORE a mutating call runs, then re-verify
509
- // the file hasn't moved out from under it before actually writing. Everything
510
- // below is pure preparation: it never writes to disk on its own except
511
- // applyWriteChecked/applyEditChecked, which are the only functions engine.js
512
- // calls once the user has approved.
513
-
514
- /** exec/writeFile/editFile/installHooks change machine state (installHooks
515
- * writes git config); listDir/glob/grep/readFile/hooks never do — this is the
516
- * set the approval gate checks against. */
517
- const MUTATING_TOOLS = new Set(['exec', 'writeFile', 'editFile', 'installHooks']);
518
-
519
- function sha256(text) {
520
- return crypto.createHash('sha256').update(text == null ? '' : text, 'utf8').digest('hex');
521
- }
522
-
523
- /** Read a file for a preview/hash snapshot. Distinguishes "doesn't exist yet"
524
- * (ok, exists:false) from a real read failure (permissions, is a directory —
525
- * ok:false), so callers can tell a brand-new file from a broken path. */
526
- function readForPreview(file_path) {
527
- try {
528
- if (!fs.existsSync(file_path)) return { ok: true, exists: false, content: null };
529
- if (fs.statSync(file_path).isDirectory()) {
530
- return { ok: false, error: `${file_path} is a directory` };
531
- }
532
- return { ok: true, exists: true, content: fs.readFileSync(file_path, 'utf8') };
533
- } catch (e) {
534
- return { ok: false, error: e && e.message ? e.message : String(e) };
535
- }
536
- }
537
-
538
- /** Classic LCS line diff: returns the {type:'equal'|'delete'|'insert', a, b}
539
- * op list turning array `a` into array `b`, indices into each array. */
540
- function diffLines(a, b) {
541
- const n = a.length;
542
- const m = b.length;
543
- const dp = new Array(n + 1);
544
- for (let i = 0; i <= n; i++) dp[i] = new Int32Array(m + 1);
545
- for (let i = n - 1; i >= 0; i--) {
546
- for (let j = m - 1; j >= 0; j--) {
547
- dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
548
- }
549
- }
550
- const ops = [];
551
- let i = 0;
552
- let j = 0;
553
- while (i < n && j < m) {
554
- if (a[i] === b[j]) {
555
- ops.push({ type: 'equal', a: i, b: j });
556
- i++;
557
- j++;
558
- } else if (dp[i + 1][j] >= dp[i][j + 1]) {
559
- ops.push({ type: 'delete', a: i });
560
- i++;
561
- } else {
562
- ops.push({ type: 'insert', b: j });
563
- j++;
564
- }
565
- }
566
- while (i < n) ops.push({ type: 'delete', a: i++ });
567
- while (j < m) ops.push({ type: 'insert', b: j++ });
568
- return ops;
569
- }
570
-
571
- /** Group an op list into unified-diff hunks (git diff -Ucontext style) and
572
- * render them as text with a/b line numbers in the @@ headers. */
573
- function formatUnifiedDiff(ops, a, b, { label, context }) {
574
- const n = ops.length;
575
- const keep = new Array(n).fill(false);
576
- for (let i = 0; i < n; i++) {
577
- if (ops[i].type === 'equal') continue;
578
- keep[i] = true;
579
- for (let k = 1; k <= context; k++) {
580
- if (i - k >= 0) keep[i - k] = true;
581
- if (i + k < n) keep[i + k] = true;
582
- }
583
- }
584
- const hunkRanges = [];
585
- let start = -1;
586
- for (let i = 0; i <= n; i++) {
587
- if (i < n && keep[i]) {
588
- if (start === -1) start = i;
589
- } else if (start !== -1) {
590
- hunkRanges.push([start, i - 1]);
591
- start = -1;
592
- }
593
- }
594
- if (!hunkRanges.length) return `--- ${label}\n+++ ${label}\n(no changes)`;
595
-
596
- const out = [`--- ${label}`, `+++ ${label}`];
597
- for (const [s, e] of hunkRanges) {
598
- let aLine = 1;
599
- let bLine = 1;
600
- for (let i = 0; i < s; i++) {
601
- if (ops[i].type !== 'insert') aLine++;
602
- if (ops[i].type !== 'delete') bLine++;
603
- }
604
- let aCount = 0;
605
- let bCount = 0;
606
- const body = [];
607
- for (let i = s; i <= e; i++) {
608
- const op = ops[i];
609
- if (op.type === 'equal') {
610
- body.push(` ${a[op.a]}`);
611
- aCount++;
612
- bCount++;
613
- } else if (op.type === 'delete') {
614
- body.push(`-${a[op.a]}`);
615
- aCount++;
616
- } else {
617
- body.push(`+${b[op.b]}`);
618
- bCount++;
619
- }
620
- }
621
- out.push(`@@ -${aLine},${aCount} +${bLine},${bCount} @@`);
622
- out.push(...body);
623
- }
624
- return out.join('\n');
625
- }
626
-
627
- /** Unified diff between two whole-file strings (`before` may be null — a new
628
- * file). Falls back to a one-line summary for files too large to diff cheaply. */
629
- function unifiedDiff(before, after, { label = 'file', context = 3 } = {}) {
630
- const a = before == null ? [] : String(before).split('\n');
631
- const b = after == null ? [] : String(after).split('\n');
632
- if (a.length > DIFF_MAX_LINES || b.length > DIFF_MAX_LINES || a.length * b.length > DIFF_MAX_CELLS) {
633
- const added = Math.max(0, b.length - a.length);
634
- const removed = Math.max(0, a.length - b.length);
635
- return `--- ${label}\n+++ ${label}\n@@ file too large to preview — approx +${added}/-${removed} lines @@`;
636
- }
637
- return formatUnifiedDiff(diffLines(a, b), a, b, { label, context });
638
- }
639
-
640
- /** Build the {before, after, diff, hash} preview for a writeFile call without
641
- * touching disk. `hash` is the sha256 of the CURRENT on-disk content (null
642
- * for a not-yet-existing file) — the snapshot applyWriteChecked re-verifies
643
- * against before actually writing. */
644
- function previewWriteFile({ file_path, content } = {}) {
645
- if (!file_path) return { ok: false, error: 'file_path is required' };
646
- const read = readForPreview(file_path);
647
- if (!read.ok) return { ok: false, error: read.error };
648
- const before = read.exists ? read.content : null;
649
- const after = String(content == null ? '' : content);
650
- return {
651
- ok: true,
652
- before,
653
- after,
654
- diff: unifiedDiff(before, after, { label: file_path }),
655
- hash: before == null ? null : sha256(before),
656
- };
657
- }
658
-
659
- /** Same shape as previewWriteFile, for editFile — shares its validation with
660
- * the executor above so there is exactly one place that knows how to apply
661
- * an edit. */
662
- function previewEditFile({ file_path, old_string, new_string, replace_all } = {}) {
663
- if (!file_path) return { ok: false, error: 'file_path is required' };
664
- if (old_string === undefined || old_string === '') {
665
- return { ok: false, error: 'old_string is required and must be non-empty' };
666
- }
667
- const read = readForPreview(file_path);
668
- if (!read.ok) return { ok: false, error: read.error };
669
- if (!read.exists) return { ok: false, error: `${file_path} does not exist` };
670
- const before = read.content;
671
- const count = before.split(old_string).length - 1;
672
- if (count === 0) return { ok: false, error: `old_string not found in ${file_path}` };
673
- if (count > 1 && !replace_all) {
674
- return { ok: false, error: `old_string is not unique (${count} matches) — use replace_all or more context` };
675
- }
676
- const after = replace_all
677
- ? before.split(old_string).join(new_string == null ? '' : new_string)
678
- : before.replace(old_string, new_string == null ? '' : new_string);
679
- return {
680
- ok: true,
681
- before,
682
- after,
683
- diff: unifiedDiff(before, after, { label: file_path }),
684
- hash: sha256(before),
685
- count,
686
- };
687
- }
688
-
689
- /** Dispatch a preview by tool name. Only writeFile/editFile have one — exec
690
- * has nothing to diff, and the approval gate skips this call for it. */
691
- function previewMutation(name, args, ctx = {}) {
692
- const norm = normalizeArgs(name, args, ctx);
693
- if (!norm.ok) return { ok: false, error: norm.error };
694
- if (name === 'writeFile') return previewWriteFile(norm.args);
695
- if (name === 'editFile') return previewEditFile(norm.args);
696
- return { ok: false, error: `no diff preview for ${name}` };
697
- }
698
-
699
- /** Apply a writeFile the user has approved, but only if the file on disk
700
- * still matches the hash captured at preview time — otherwise something
701
- * else changed it while the approval card was open, and applying blind
702
- * would silently clobber that change. */
703
- function applyWriteChecked({ file_path, content } = {}, expectedHash) {
704
- try {
705
- if (!file_path) return fail('file_path is required');
706
- const read = readForPreview(file_path);
707
- if (!read.ok) return fail(read.error);
708
- const currentHash = read.exists ? sha256(read.content) : null;
709
- if (currentHash !== expectedHash) {
710
- return fail(
711
- `${file_path} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`
712
- );
713
- }
714
- fs.mkdirSync(path.dirname(file_path), { recursive: true });
715
- fs.writeFileSync(file_path, String(content == null ? '' : content), 'utf8');
716
- return ok(`Wrote ${String(content == null ? '' : content).length} bytes to ${file_path}`);
717
- } catch (e) {
718
- return fail(e && e.message ? e.message : String(e));
719
- }
720
- }
721
-
722
- /** Same guard as applyWriteChecked, for an already-computed editFile result
723
- * (`after` — the preview's replacement, not recomputed here since a hash
724
- * match means the source it was computed from is still exactly on disk). */
725
- function applyEditChecked({ file_path, after } = {}, expectedHash) {
726
- try {
727
- if (!file_path) return fail('file_path is required');
728
- const read = readForPreview(file_path);
729
- if (!read.ok) return fail(read.error);
730
- const currentHash = read.exists ? sha256(read.content) : null;
731
- if (currentHash !== expectedHash) {
732
- return fail(
733
- `${file_path} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`
734
- );
735
- }
736
- fs.writeFileSync(file_path, after, 'utf8');
737
- return ok(`Edited ${file_path}`);
738
- } catch (e) {
739
- return fail(e && e.message ? e.message : String(e));
740
- }
741
- }
742
-
743
- /** Apply an approved writeFile/editFile call using the hash captured in its
744
- * `preview` (see previewMutation) — the single entry point engine.js calls
745
- * once the user has said yes. */
746
- function applyChecked(name, args, preview, ctx = {}) {
747
- const norm = normalizeArgs(name, args, ctx);
748
- if (!norm.ok) return fail(norm.error);
749
- if (name === 'writeFile') return applyWriteChecked(norm.args, preview.hash);
750
- return applyEditChecked({ file_path: norm.args.file_path, after: preview.after }, preview.hash);
751
- }
752
-
753
- const IGNORED_DIRS = new Set(['node_modules', '.git', 'dist', '.aegiscode']);
754
-
755
- function listDir({ path: dir } = {}, ctx = {}) {
756
- try {
757
- const base = dir || baseDir(ctx);
758
- const entries = fs.readdirSync(base, { withFileTypes: true });
759
- const rows = entries
760
- .filter((e) => !IGNORED_DIRS.has(e.name))
761
- .map((e) => (e.isDirectory() ? `${e.name}/` : e.name))
762
- .sort((a, b) => a.localeCompare(b));
763
- return ok(rows.join('\n') || '(empty directory)');
764
- } catch (e) {
765
- return fail(e && e.message ? e.message : String(e));
766
- }
767
- }
768
-
769
- /** Translate a glob into a regex over '/'-separated relative paths. */
770
- function globToRegex(pattern) {
771
- let re = '^';
772
- for (let i = 0; i < pattern.length; i++) {
773
- const c = pattern[i];
774
- if (c === '*') {
775
- if (pattern[i + 1] === '*') {
776
- re += '.*';
777
- i++;
778
- } else re += '[^/]*';
779
- } else if (c === '?') re += '[^/]';
780
- else if (/[.+^${}()|[\]\\]/.test(c)) re += `\\${c}`;
781
- else re += c;
782
- }
783
- return new RegExp(re + '$');
784
- }
785
-
786
- function walk(dir, fn, depth = 0) {
787
- if (depth > 12) return; // hard bound: never crawl an unbounded tree
788
- let entries;
789
- try {
790
- entries = fs.readdirSync(dir, { withFileTypes: true });
791
- } catch {
792
- return;
793
- }
794
- for (const e of entries) {
795
- if (IGNORED_DIRS.has(e.name)) continue;
796
- const full = path.join(dir, e.name);
797
- if (e.isDirectory()) walk(full, fn, depth + 1);
798
- else fn(full);
799
- }
800
- }
801
-
802
- function glob({ pattern, path: root } = {}, ctx = {}) {
803
- try {
804
- if (!pattern) return fail('pattern is required');
805
- const base = root || baseDir(ctx);
806
- const re = globToRegex(String(pattern));
807
- const hits = [];
808
- walk(base, (full) => {
809
- if (hits.length >= MATCH_CAP) return;
810
- const rel = path.relative(base, full).split(path.sep).join('/');
811
- if (re.test(rel)) hits.push(rel);
812
- });
813
- return ok(hits.join('\n') || '(no matches)');
814
- } catch (e) {
815
- return fail(e && e.message ? e.message : String(e));
816
- }
817
- }
818
-
819
- function grep({ pattern, path: root } = {}, ctx = {}) {
820
- try {
821
- if (!pattern) return fail('pattern is required');
822
- const re = new RegExp(pattern);
823
- const base = root || baseDir(ctx);
824
- const hits = [];
825
- walk(base, (full) => {
826
- if (hits.length >= MATCH_CAP) return;
827
- let text;
828
- try {
829
- // Skip oversized files (logs, dumps, binaries) instead of slurping
830
- // them — a 10 GB log would otherwise stall the whole tool loop.
831
- if (fs.statSync(full).size > GREP_SIZE_CAP) return;
832
- text = fs.readFileSync(full, 'utf8');
833
- } catch {
834
- return;
835
- }
836
- const rel = path.relative(base, full).split(path.sep).join('/');
837
- for (const [i, line] of text.split('\n').entries()) {
838
- if (hits.length >= MATCH_CAP) return;
839
- if (re.test(line)) hits.push(`${rel}:${i + 1}: ${line.slice(0, 160)}`);
840
- }
841
- });
842
- return ok(hits.join('\n') || '(no matches)');
843
- } catch (e) {
844
- return fail(e && e.message ? e.message : String(e));
845
- }
846
- }
847
-
848
- /**
849
- * Run a shell command as a fresh one-shot process (no state carried to the
850
- * next call). Never rejects: spawn failures, a stalled child, a non-zero
851
- * exit and output overflow all resolve as `{ ok:false, error }` (a non-zero
852
- * exit is reported as an error so the model sees the failure, with whatever
853
- * the command printed attached).
854
- */
855
- function execOneShot({ command, cwd, timeout, maxBuffer } = {}) {
856
- return new Promise((resolve) => {
857
- const limit = Math.min(Number(maxBuffer) || EXEC_MAX_BUFFER, EXEC_MAX_BUFFER);
858
- const ms = Math.min(Number(timeout) || EXEC_TIMEOUT_DEFAULT, EXEC_TIMEOUT_CAP);
859
- // Shell to run `exec` in: PowerShell on Windows (both the persistent
860
- // session AND the one-shot path — they must agree, or a session that dies
861
- // mid-turn silently switches the quoting contract; see shell.js
862
- // resolveSessionShell), a PROBED POSIX sh/bash elsewhere. The choice, the
863
- // platform seam that makes its win32 half testable on Linux and the
864
- // fish/csh/nu refusal all live in client/platform.js + shell.js (Phase
865
- // 30.1/30.3) — there is no second copy of that decision here, and an
866
- // unverifiable shell is REPORTED rather than used.
867
- const spec = shells.oneShotShellSpec();
868
- if (!spec.ok) {
869
- resolve(fail(spec.error));
870
- return;
871
- }
872
- const { cmd, arg } = spec;
873
-
874
- let child;
875
- try {
876
- child = spawn(cmd, [arg, command], {
877
- cwd: cwd || process.cwd(),
878
- timeout: ms,
879
- killSignal: 'SIGKILL',
880
- windowsHide: true,
881
- });
882
- } catch (e) {
883
- resolve(fail(`spawn failed: ${e && e.message ? e.message : e}`));
884
- return;
885
- }
886
-
887
- let out = '';
888
- let bytes = 0;
889
- let overflow = false;
890
- let timedOut = false;
891
- let settled = false;
892
-
893
- const timer = setTimeout(() => {
894
- timedOut = true;
895
- try {
896
- child.kill('SIGKILL');
897
- } catch {
898
- /* already gone */
899
- }
900
- }, ms);
901
-
902
- const collect = (chunk) => {
903
- bytes += chunk.length;
904
- if (bytes > limit) {
905
- overflow = true;
906
- try {
907
- child.kill('SIGKILL');
908
- } catch {
909
- /* already gone */
910
- }
911
- return;
912
- }
913
- out += chunk;
914
- };
915
-
916
- if (child.stdout) child.stdout.on('data', collect);
917
- if (child.stderr) child.stderr.on('data', collect);
918
-
919
- const done = (res) => {
920
- if (settled) return;
921
- settled = true;
922
- clearTimeout(timer);
923
- resolve(res);
924
- };
925
-
926
- child.on('error', (e) => done(fail(`spawn failed: ${e && e.message ? e.message : e}`)));
927
- child.on('close', (code, signal) => {
928
- const body = out.trim();
929
- if (timedOut) {
930
- done(fail(`command timed out after ${ms}ms${body ? `\n${body}` : ''}`));
931
- return;
932
- }
933
- if (overflow) {
934
- // The buffer cap is what the model should see: trimming to OUTPUT_CAP
935
- // below would hide the fact that output was dropped.
936
- done(fail(`output exceeded ${limit} bytes and was truncated\n${body}`));
937
- return;
938
- }
939
- const label = `exit ${code == null ? `signal ${signal}` : code}`;
940
- if (code === 0) done(ok(body || `(${label}, no output)`));
941
- else done(fail(`${label}${body ? `\n${body}` : ''}`));
942
- });
943
- });
944
- }
945
-
946
- /**
947
- * Run a persistent-session command and translate the session's { content,
948
- * isError } shape into this file's { ok, output } / { ok:false, error }
949
- * convention. An abort signal disposes the session immediately instead of
950
- * waiting out the command's own timeout.
951
- */
952
- function execInShell(shell, { command, cwd, timeout }, signal) {
953
- if (signal && signal.aborted) {
954
- shell.dispose();
955
- return Promise.resolve(fail('aborted'));
956
- }
957
- return new Promise((resolve) => {
958
- const onAbort = () => shell.dispose();
959
- if (signal) signal.addEventListener('abort', onAbort, { once: true });
960
- const release = () => { if (signal) signal.removeEventListener('abort', onAbort); };
961
- shell.run(command, { timeout, working_directory: cwd }).then(
962
- (r) => { release(); resolve(r.isError ? fail(r.content) : ok(r.content)); },
963
- (e) => { release(); resolve(fail(`shell session failed: ${e && e.message ? e.message : e}`)); }
964
- );
965
- });
966
- }
967
-
968
- /**
969
- * Execute a shell command. When the caller supplies `ctx.getShell` (the
970
- * chat loop always does — see engine.js), the command runs in that turn's
971
- * persistent session so cd/export/env state carries to the next call. Without
972
- * one (e.g. a direct executeTool call in tests) it falls back to a one-shot
973
- * spawn — same output shape, no persisted state. Never rejects.
974
- */
975
- function exec({ command, cwd, timeout, maxBuffer } = {}, ctx = {}) {
976
- if (!command || typeof command !== 'string') {
977
- return Promise.resolve(fail('command is required'));
978
- }
979
- const shell = typeof ctx.getShell === 'function' ? ctx.getShell() : null;
980
- if (shell) return execInShell(shell, { command, cwd, timeout }, ctx.signal);
981
- return execOneShot({ command, cwd, timeout, maxBuffer });
982
- }
983
-
984
- // ── hooks / installHooks ────────────────────────────────────────────────────
985
- //
986
- // The hook layer is SHARED with the CLI (`client/hooks.js`, the same file
987
- // `aegiscode /hooks` reads and `agent-gate.mjs install-hooks` installs), loaded
988
- // exactly like the other cross-host modules: the repo-relative path first,
989
- // then the flattened staged copy inside the app dir. Two implementations of
990
- // "which settings files count" is how the GUI and the terminal end up
991
- // describing one machine differently — which is what this replaced.
992
- //
993
- // Before this, the desktop had NO hook surface at all: the app could open a
994
- // guarded tree and never mention that the git-side half of the same lock was
995
- // not installed, so a fresh clone committed with no gate and nothing said so.
996
- let hooksLib = null;
997
- try {
998
- hooksLib = require('../../../client/hooks.js');
999
- } catch {
1000
- try { hooksLib = require('../../vendor/hooks.js'); } catch { hooksLib = null; }
1001
- }
1002
-
1003
- const HOOKS_LIB_MISSING =
1004
- 'the shared hook module could not be loaded (tried client/hooks.js beside the app and '
1005
- + 'vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.';
1006
-
1007
- function hooksListing(config) {
1008
- const lines = [];
1009
- const hooks = config && config.hooks ? config.hooks : {};
1010
- for (const [event, matchers] of Object.entries(hooks)) {
1011
- lines.push(`${event} (${matchers.length})`);
1012
- for (const matcher of matchers) {
1013
- if (!matcher) continue;
1014
- lines.push(` - ${matcher.name || '(unnamed)'}`);
1015
- const m = matcher.matcher;
1016
- if (m && m.tools) lines.push(` tools: ${m.tools}`);
1017
- if (m && m.paths) lines.push(` paths: ${m.paths}`);
1018
- if (m && m.commands) lines.push(` commands: ${m.commands}`);
1019
- }
1020
- }
1021
- return lines.length ? lines.join('\n') : '(no hooks declared in any settings file)';
1022
- }
1023
-
1024
- /** Read-only: hook config + whether this repo's guard hooks are installed. */
1025
- function hooks({ sub, cwd } = {}) {
1026
- if (!hooksLib) return fail(HOOKS_LIB_MISSING);
1027
- try {
1028
- const opts = { cwd: cwd || process.cwd() };
1029
- const config = hooksLib.readHookConfig(opts);
1030
- if (String(sub || 'status').toLowerCase() === 'list') return ok(hooksListing(config));
1031
- const stats = hooksLib.hookStats(config.hooks);
1032
- return ok(hooksLib.hooksSummary({ ...opts, config, stats }));
1033
- } catch (e) {
1034
- return fail(e && e.message ? e.message : String(e));
1035
- }
1036
- }
1037
-
1038
- /** Mutating: install the repo's guard hooks (core.hooksPath -> .githooks/). */
1039
- function installHooks({ cwd, dry_run } = {}) {
1040
- if (!hooksLib) return fail(HOOKS_LIB_MISSING);
1041
- let res;
1042
- try {
1043
- res = hooksLib.installRepoHooks({ cwd: cwd || process.cwd(), dryRun: Boolean(dry_run) });
1044
- } catch (e) {
1045
- return fail(e && e.message ? e.message : String(e));
1046
- }
1047
- const plan = res.actions.length ? `\n ${res.actions.join('\n ')}` : '';
1048
- if (!res.ok) return fail(`${res.error}${plan}`);
1049
- if (dry_run) {
1050
- return ok(`would install the guard hooks in ${res.status.repo}${plan || '\n (already installed — nothing to do)'}`
1051
- + (res.status.installed ? '' : '\n re-run without dry_run to apply'));
1052
- }
1053
- if (!res.changed) {
1054
- return ok(`guard hooks already installed in ${res.status.repo}: core.hooksPath = .githooks\n ${res.status.execNote}`);
1055
- }
1056
- return ok(`guard hooks installed in ${res.status.repo}\n core.hooksPath = .githooks (verified by reading it back)`
1057
- + `${plan}\n ${res.status.execNote}\n a commit and a push in this tree are now gated.`);
1058
- }
1059
-
1060
- const EXECUTORS = { readFile, writeFile, editFile, listDir, glob, grep, exec, hooks, installHooks };
1061
-
1062
- /** True when `name` is a tool this layer can run (task is excluded — see SUBAGENT_TOOL). */
1063
- function isTool(name) {
1064
- return Object.prototype.hasOwnProperty.call(EXECUTORS, name);
1065
- }
1066
-
1067
- /**
1068
- * Execute one tool call. Always resolves `{ ok, output }` or `{ ok, error }`
1069
- * — an unknown tool name, a non-object args payload and an exploding executor
1070
- * all land on the error branch rather than rejecting. `ctx` carries per-turn
1071
- * state (getShell, signal); omit it and exec falls back to a one-shot spawn.
1072
- */
1073
- /**
1074
- * `tools/agent-gate.mjs` is ESM and this module is CJS, so it is imported
1075
- * dynamically and once. The candidates are tried in order; the first that
1076
- * resolves wins:
1077
- *
1078
- * 1. `../../../tools/agent-gate.mjs` — the repo checkout (dev / CI). This is
1079
- * the SAME file the git hooks execute, so "what is allowed" is computed
1080
- * once, by one implementation.
1081
- * 2. `<process.resourcesPath>/tools/agent-gate.mjs` — where electron-builder's
1082
- * `extraResources` puts it in a packaged build, as a real file OUTSIDE the
1083
- * asar. That placement is load-bearing, not cosmetic: the gate is loaded
1084
- * with dynamic `import()`, and Node's ESM loader does not go through
1085
- * Electron's asar-aware fs patch (electron/asar#249), so a copy living only
1086
- * inside the archive can fail to resolve — leaving the packaged app with no
1087
- * gate at all. This is the app's only dynamic ESM import, so nothing else
1088
- * here exercises that path. Conveniently this is also what candidate (1)
1089
- * resolves to from `resources/app.asar/lib/local/`, so dev and packaged
1090
- * builds agree on one file.
1091
- * 3. `../../vendor/agent-gate.mjs` — the staged copy inside the app dir, kept
1092
- * as the last resort for a build that is not archived (`asar: false`) or an
1093
- * npm-installed tree. It is the candidate that fails inside an asar, hence
1094
- * third and not first.
1095
- *
1096
- * Before (2) existed a packaged build had no gate at all: the manifest is found
1097
- * by climbing from the working directory, so the packaged app would open a
1098
- * guarded tree and every write through it succeeded while the same call through
1099
- * the repo copy was refused.
1100
- *
1101
- * If nothing resolves, that is a broken gate rather than a permissive one, and
1102
- * executeTool refuses mutating calls into a tree that declares a manifest.
1103
- */
1104
- let agentGatePromise;
1105
-
1106
- function agentGateCandidates({ resourcesPath = process.resourcesPath, dirname = __dirname } = {}) {
1107
- const candidates = ['../../../tools/agent-gate.mjs'];
1108
- // process.resourcesPath is an Electron-provided value and is absent under
1109
- // plain node, so this is guarded rather than assumed. An absolute path must
1110
- // be a file URL to be imported.
1111
- if (typeof resourcesPath === 'string' && resourcesPath) {
1112
- candidates.push(pathToFileURL(path.join(resourcesPath, 'tools', 'agent-gate.mjs')).href);
1113
- }
1114
- candidates.push('../../vendor/agent-gate.mjs');
1115
- return candidates;
1116
- }
1117
-
1118
- function loadAgentGate() {
1119
- if (!agentGatePromise) {
1120
- const candidates = agentGateCandidates();
1121
- const tryNext = (i) => (i >= candidates.length
1122
- ? null
1123
- : import(candidates[i]).catch(() => tryNext(i + 1)));
1124
- agentGatePromise = tryNext(0);
1125
- }
1126
- return agentGatePromise;
1127
- }
1128
-
1129
- /**
1130
- * The nearest `.aegis/guard.json` at or above `start`, or null. The identical
1131
- * climb as findManifest() in tools/agent-gate.mjs and src/repoguard.js. It is
1132
- * used ONLY to decide whether a call that could not load the gate module is
1133
- * unsafe; when the module loads it is the sole authority.
1134
- */
1135
- function nearestManifest(start) {
1136
- let dir = path.resolve(start || process.cwd());
1137
- try { if (fs.statSync(dir).isFile()) dir = path.dirname(dir); } catch { /* keep as-is */ }
1138
- for (;;) {
1139
- const candidate = path.join(dir, '.aegis', 'guard.json');
1140
- if (fs.existsSync(candidate)) return candidate;
1141
- const parent = path.dirname(dir);
1142
- if (parent === dir) return null;
1143
- dir = parent;
1144
- }
1145
- }
1146
-
1147
- async function executeTool(name, args, ctx) {
1148
- if (!isTool(name)) return fail(`unknown tool "${name}" (known: ${toolNames().join(', ')})`);
1149
- // Paths become real BEFORE the agent-key gate below resolves them itself —
1150
- // see normalizeArgs. A `~/…` that reached the gate unexpanded was ruled on as
1151
- // `<cwd>/~/…`, i.e. a different file than the one about to be written.
1152
- const norm = normalizeArgs(name, args, ctx || {});
1153
- if (!norm.ok) return fail(norm.error);
1154
- const input = norm.args;
1155
- // ── agent-key gate (tools/agent-gate.mjs) ──────────────────────────────
1156
- // The in-process half of the lock whose other half is .githooks/. A tree
1157
- // that declares .aegis/guard.json must not be mutated through this app
1158
- // without the key, exactly as it cannot be mutated by the engine or
1159
- // committed by git. Reads are never gated. Refused — not warned — when the
1160
- // key is absent, the manifest is unreadable, or the key file is
1161
- // world-readable; AEGIS_GATE_SKIP=1 is the one bypass, and it is refused in
1162
- // an unattended run. The module is required lazily so a packaged app whose
1163
- // tree has no tools/ directory still starts and simply has no gate.
1164
- let gate = null;
1165
- try {
1166
- gate = await loadAgentGate();
1167
- } catch { /* not running from the repo: no manifest to honour */ }
1168
- if (gate) {
1169
- const verdict = gate.guardTool({
1170
- tool: name, args: input, cwd: (ctx && ctx.cwd) || process.cwd(),
1171
- env: process.env, unattended: Boolean(ctx && ctx.autonomous),
1172
- });
1173
- if (!verdict.allowed) return fail(gate.refusalText(verdict));
1174
- if (verdict.code === 'skipped') {
1175
- const res = await EXECUTORS[name](input, ctx || {});
1176
- return res && typeof res === 'object' ? { ...res, output: `⚠ ${verdict.reason}\n${res.output || ''}` } : res;
1177
- }
1178
- } else if (MUTATING_TOOLS.has(name)) {
1179
- // Neither the repo copy nor the staged one loaded. A broken gate must
1180
- // never silently allow (the hooks exit 4 for exactly this reason), so a
1181
- // mutating call into a tree that declares a manifest is refused with the
1182
- // path of the manifest that could not be honoured.
1183
- const man = nearestManifest((ctx && ctx.cwd) || process.cwd());
1184
- if (man) {
1185
- return fail(
1186
- `error: refused — ${man} declares an agent-gated tree, but the agent-key gate module could not be loaded `
1187
- + '(tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this '
1188
- + `${name} cannot be authorised. A build that missed the staged copy is the usual cause: `
1189
- + 'run scripts/predist.mjs before packaging.',
1190
- );
1191
- }
1192
- }
1193
- try {
1194
- return await EXECUTORS[name](input, ctx || {});
1195
- } catch (e) {
1196
- return fail(e && e.message ? e.message : String(e));
1197
- }
1198
- }
1199
-
1200
- /**
1201
- * The string a tool result contributes to the conversation: the output on
1202
- * success, `error: …` on failure — the same shape the CLI feeds back.
1203
- */
1204
- function toolResultText(result) {
1205
- if (!result) return 'error: tool produced no result';
1206
- return result.ok ? String(result.output == null ? '' : result.output) : `error: ${result.error}`;
1207
- }
1208
-
1209
- module.exports = {
1210
- // schemas
1211
- SCHEMAS,
1212
- SUBAGENT_TOOL,
1213
- HOOK_TOOLS,
1214
- toolNames,
1215
- openaiTools,
1216
- toolsFor,
1217
- // execution
1218
- executeTool,
1219
- isTool,
1220
- toolResultText,
1221
- // approval gate (desktop/lib/local/engine.js gatedExecuteTool)
1222
- MUTATING_TOOLS,
1223
- previewMutation,
1224
- applyChecked,
1225
- // path handling (client/platform.js resolvePath applied to a tool call)
1226
- normalizeArgs,
1227
- TOOL_PATH_ARGS,
1228
- PATH_ARG_DESC,
1229
- // limits (unit tests assert against them instead of hard-coding numbers)
1230
- OUTPUT_CAP,
1231
- READ_LINE_CAP,
1232
- MATCH_CAP,
1233
- READ_SIZE_CAP,
1234
- GREP_SIZE_CAP,
1235
- EXEC_TIMEOUT_DEFAULT,
1236
- EXEC_TIMEOUT_CAP,
1237
- EXEC_MAX_BUFFER,
1238
- DIFF_MAX_CELLS,
1239
- DIFF_MAX_LINES,
1240
- };
3
+ "use strict";const{spawn:spawn}=require("node:child_process"),crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),{pathToFileURL:pathToFileURL}=require("node:url"),{agentRoles:agentRoles}=require("./agents.js");let platform;try{platform=require("../../../client/platform.js")}catch(e){try{platform=require("../../vendor/platform.js")}catch{throw new Error(`tools.js: cannot load the shared platform module (client/platform.js, or its staged copy): ${e&&e.message?e.message:e}`)}}const OUTPUT_CAP=3e4,PATH_ARG_DESC='Absolute path on THIS machine; "~"/"~/…" = home. Relative resolves against the working directory.',pathDesc=e=>`${e}. ${PATH_ARG_DESC}`,shells=require("./shell.js"),READ_LINE_CAP=2e3,MATCH_CAP=100,READ_SIZE_CAP=26214400,GREP_SIZE_CAP=10485760,EXEC_TIMEOUT_DEFAULT=12e4,EXEC_TIMEOUT_CAP=6e5,EXEC_MAX_BUFFER=1048576,DIFF_MAX_CELLS=4e6,DIFF_MAX_LINES=2e4;function cap(e){const t=String(null==e?"":e);return t.length>3e4?`${t.slice(0,3e4)}\n… (truncated)`:t}const ok=e=>({ok:!0,output:cap(e)}),fail=e=>({ok:!1,error:cap(e)}),SCHEMAS={readFile:{name:"readFile",description:"Read a file. Returns line-numbered content.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to read")},offset:{type:"number",description:"Start line (0-based)"},limit:{type:"number",description:"The number of lines to read (max 10000, default 2000)"}},required:["file_path"],additionalProperties:!1}},writeFile:{name:"writeFile",description:"Write a whole file, overwriting it. Parent dirs are created. Use editFile to change part of one.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to write")},content:{type:"string",description:"Full file contents"}},required:["file_path","content"],additionalProperties:!1}},editFile:{name:"editFile",description:"Exact string replacement. old_string must be unique unless replace_all. Fails loudly on a missing or ambiguous match rather than guessing.",parameters:{type:"object",properties:{file_path:{type:"string",description:pathDesc("The file to edit")},old_string:{type:"string",description:"Text to replace; must be unique unless replace_all"},new_string:{type:"string",description:"Replacement text"},replace_all:{type:"boolean",description:"Replace every occurrence"}},required:["file_path","old_string","new_string"],additionalProperties:!1}},listDir:{name:"listDir",description:"List one directory (non-recursive). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{path:{type:"string",description:pathDesc("The directory to list (default: the working directory)")}},required:[],additionalProperties:!1}},glob:{name:"glob",description:"Find files by glob (**, *, ?). Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob, e.g. "**/*.test.js"'},path:{type:"string",description:pathDesc("Search root (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},grep:{name:"grep",description:"Search file contents by regex. Returns file:line matches. Skips node_modules, .git, dist.",parameters:{type:"object",properties:{pattern:{type:"string",description:"The regular expression to search for"},path:{type:"string",description:pathDesc("The directory to search in (default: the working directory)")}},required:["pattern"],additionalProperties:!1}},exec:{name:"exec",description:"Run a shell command in a PERSISTENT session: cd and exported env carry across calls in this turn. Returns stdout+stderr and the exit code. Use for git, packages, system ops.",parameters:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:pathDesc("Run this one command elsewhere; session cwd unchanged")},timeout:{type:"number",description:`Timeout in milliseconds (max ${EXEC_TIMEOUT_CAP}, default ${EXEC_TIMEOUT_DEFAULT})`},description:{type:"string",description:"A brief description of what the command does (for display)"}},required:["command"],additionalProperties:!1}},hooks:{name:"hooks",description:"Hook status for this machine, from the same shared implementation the CLI's /hooks uses: the merged settings.json hook config (~/.aegis, ./.aegis, ~/.aegiscode, ./.aegiscode, ~/.claude) and whether this repo's .githooks/ guard hooks are actually installed (core.hooksPath). Read-only. Use installHooks to install them.",parameters:{type:"object",properties:{sub:{type:"string",enum:["status","list"],description:"status (default) or the full config listing"},cwd:{type:"string",description:pathDesc("Repo to inspect (default: the working directory)")}},required:[],additionalProperties:!1}},installHooks:{name:"installHooks",description:"Install this repo's guard hooks: point git's core.hooksPath at .githooks/ (the agent-key gate, the secret scan, the invariant lock) and make them executable. Idempotent, and verified by reading the config back. Pass dry_run to see the exact commands without running them. Without this, a fresh clone runs NO guard hooks.",parameters:{type:"object",properties:{cwd:{type:"string",description:pathDesc("Repo to install into (default: the working directory)")},dry_run:{type:"boolean",description:"Print the commands instead of running them"}},required:[],additionalProperties:!1}},task:{name:"task",description:"Delegate a focused multi-step sub-task to a subagent with its own tool loop; it returns a final report. Give it a complete, self-contained prompt — it cannot ask follow-ups.",parameters:{type:"object",properties:{description:{type:"string",description:"Short label (3-5 words)"},subagent_type:{type:"string",enum:[...agentRoles(),"general"],description:"Which specialist preset to spawn (general = a capable all-purpose agent)"},prompt:{type:"string",description:"The full, self-contained task instructions for the subagent"}},required:["description","prompt"],additionalProperties:!1}}},SUBAGENT_TOOL="task",HOOK_TOOLS=new Set(["hooks","installHooks"]);function toolNames({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>e.name))}function schemaList({includeSubagent:e=!0,includeHooks:t=!1}={}){return Object.values(SCHEMAS).filter((r=>(e||r.name!==SUBAGENT_TOOL)&&(t||!HOOK_TOOLS.has(r.name))))}function openaiTools({includeSubagent:e=!0,includeHooks:t=!1}={}){return schemaList({includeSubagent:e,includeHooks:t}).map((e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}})))}function toolsFor({includeSubagent:e=!0,includeHooks:t=!1}={}){return openaiTools({includeSubagent:e,includeHooks:t})}const TOOL_PATH_ARGS=Object.freeze({readFile:["file_path"],writeFile:["file_path"],editFile:["file_path"],listDir:["path"],glob:["path"],grep:["path"],exec:["cwd"],hooks:["cwd"],installHooks:["cwd"]});function normalizeArgs(e,t,r={}){const o=t&&"object"==typeof t?t:{},i=TOOL_PATH_ARGS[e];if(!i)return{ok:!0,args:o,error:null};let n=o;for(const t of i){const i=o[t];if("string"!=typeof i||!i.trim())continue;const s=platform.resolvePath(i,{platform:r&&r.platform?r.platform:void 0,cwd:r&&r.cwd?r.cwd:void 0,desktopdir:r&&r.desktopdir?r.desktopdir:void 0});if(!s.ok)return{ok:!1,args:o,error:`${e}: ${t} — ${s.error}`};s.path!==i&&(n===o&&(n={...o}),n[t]=s.path)}return{ok:!0,args:n,error:null}}function baseDir(e){return e&&"string"==typeof e.cwd&&e.cwd||process.cwd()}function readFile({file_path:e,offset:t=0,limit:r}={}){try{if(!e)return fail("file_path is required");const o=fs.statSync(e);if(o.isDirectory())return fail(`${e} is a directory (use listDir)`);if(o.size>26214400){const t=(o.size/1048576).toFixed(1);return fail(`${e} is ${t} MB — too large to read (limit 25 MB). Use exec with grep/head to inspect it instead.`)}const i=fs.readFileSync(e,"utf8").split("\n"),n=Math.max(0,Number(t)||0),s=Math.max(1,Math.min(Number(r)||2e3,1e4)),a=i.slice(n,n+s),l=a.map(((e,t)=>`${t+n+1}| ${e}`)).join("\n"),c=n+a.length<i.length?`\n… (${i.length-n-a.length} more lines)`:"";return ok(l+c)}catch(e){return fail(e&&e.message?e.message:String(e))}}function writeFile({file_path:e,content:t}={}){try{return e?(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail("file_path is required")}catch(e){return fail(e&&e.message?e.message:String(e))}}function editFile(e={}){try{const t=previewEditFile(e);return t.ok?(fs.writeFileSync(e.file_path,t.after,"utf8"),ok(`Edited ${e.file_path} (${t.count} occurrence${t.count>1?"s":""} replaced)`)):fail(t.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}const MUTATING_TOOLS=new Set(["exec","writeFile","editFile","installHooks"]);function sha256(e){return crypto.createHash("sha256").update(null==e?"":e,"utf8").digest("hex")}function readForPreview(e){try{return fs.existsSync(e)?fs.statSync(e).isDirectory()?{ok:!1,error:`${e} is a directory`}:{ok:!0,exists:!0,content:fs.readFileSync(e,"utf8")}:{ok:!0,exists:!1,content:null}}catch(e){return{ok:!1,error:e&&e.message?e.message:String(e)}}}function diffLines(e,t){const r=e.length,o=t.length,i=new Array(r+1);for(let e=0;e<=r;e++)i[e]=new Int32Array(o+1);for(let n=r-1;n>=0;n--)for(let r=o-1;r>=0;r--)i[n][r]=e[n]===t[r]?i[n+1][r+1]+1:Math.max(i[n+1][r],i[n][r+1]);const n=[];let s=0,a=0;for(;s<r&&a<o;)e[s]===t[a]?(n.push({type:"equal",a:s,b:a}),s++,a++):i[s+1][a]>=i[s][a+1]?(n.push({type:"delete",a:s}),s++):(n.push({type:"insert",b:a}),a++);for(;s<r;)n.push({type:"delete",a:s++});for(;a<o;)n.push({type:"insert",b:a++});return n}function formatUnifiedDiff(e,t,r,{label:o,context:i}){const n=e.length,s=new Array(n).fill(!1);for(let t=0;t<n;t++)if("equal"!==e[t].type){s[t]=!0;for(let e=1;e<=i;e++)t-e>=0&&(s[t-e]=!0),t+e<n&&(s[t+e]=!0)}const a=[];let l=-1;for(let e=0;e<=n;e++)e<n&&s[e]?-1===l&&(l=e):-1!==l&&(a.push([l,e-1]),l=-1);if(!a.length)return`--- ${o}\n+++ ${o}\n(no changes)`;const c=[`--- ${o}`,`+++ ${o}`];for(const[o,i]of a){let n=1,s=1;for(let t=0;t<o;t++)"insert"!==e[t].type&&n++,"delete"!==e[t].type&&s++;let a=0,l=0;const d=[];for(let n=o;n<=i;n++){const o=e[n];"equal"===o.type?(d.push(` ${t[o.a]}`),a++,l++):"delete"===o.type?(d.push(`-${t[o.a]}`),a++):(d.push(`+${r[o.b]}`),l++)}c.push(`@@ -${n},${a} +${s},${l} @@`),c.push(...d)}return c.join("\n")}function unifiedDiff(e,t,{label:r="file",context:o=3}={}){const i=null==e?[]:String(e).split("\n"),n=null==t?[]:String(t).split("\n");return i.length>DIFF_MAX_LINES||n.length>DIFF_MAX_LINES||i.length*n.length>DIFF_MAX_CELLS?`--- ${r}\n+++ ${r}\n@@ file too large to preview — approx +${Math.max(0,n.length-i.length)}/-${Math.max(0,i.length-n.length)} lines @@`:formatUnifiedDiff(diffLines(i,n),i,n,{label:r,context:o})}function previewWriteFile({file_path:e,content:t}={}){if(!e)return{ok:!1,error:"file_path is required"};const r=readForPreview(e);if(!r.ok)return{ok:!1,error:r.error};const o=r.exists?r.content:null,i=String(null==t?"":t);return{ok:!0,before:o,after:i,diff:unifiedDiff(o,i,{label:e}),hash:null==o?null:sha256(o)}}function previewEditFile({file_path:e,old_string:t,new_string:r,replace_all:o}={}){if(!e)return{ok:!1,error:"file_path is required"};if(void 0===t||""===t)return{ok:!1,error:"old_string is required and must be non-empty"};const i=readForPreview(e);if(!i.ok)return{ok:!1,error:i.error};if(!i.exists)return{ok:!1,error:`${e} does not exist`};const n=i.content,s=n.split(t).length-1;if(0===s)return{ok:!1,error:`old_string not found in ${e}`};if(s>1&&!o)return{ok:!1,error:`old_string is not unique (${s} matches) — use replace_all or more context`};const a=o?n.split(t).join(null==r?"":r):n.replace(t,null==r?"":r);return{ok:!0,before:n,after:a,diff:unifiedDiff(n,a,{label:e}),hash:sha256(n),count:s}}function previewMutation(e,t,r={}){const o=normalizeArgs(e,t,r);return o.ok?"writeFile"===e?previewWriteFile(o.args):"editFile"===e?previewEditFile(o.args):{ok:!1,error:`no diff preview for ${e}`}:{ok:!1,error:o.error}}function applyWriteChecked({file_path:e,content:t}={},r){try{if(!e)return fail("file_path is required");const o=readForPreview(e);return o.ok?(o.exists?sha256(o.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale write. Re-run writeFile to get an updated diff.`):(fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(null==t?"":t),"utf8"),ok(`Wrote ${String(null==t?"":t).length} bytes to ${e}`)):fail(o.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyEditChecked({file_path:e,after:t}={},r){try{if(!e)return fail("file_path is required");const o=readForPreview(e);return o.ok?(o.exists?sha256(o.content):null)!==r?fail(`${e} changed on disk since the diff was shown — refusing to apply a stale edit. Re-run editFile to get an updated diff.`):(fs.writeFileSync(e,t,"utf8"),ok(`Edited ${e}`)):fail(o.error)}catch(e){return fail(e&&e.message?e.message:String(e))}}function applyChecked(e,t,r,o={}){const i=normalizeArgs(e,t,o);return i.ok?"writeFile"===e?applyWriteChecked(i.args,r.hash):applyEditChecked({file_path:i.args.file_path,after:r.after},r.hash):fail(i.error)}const IGNORED_DIRS=new Set(["node_modules",".git","dist",".aegiscode"]);function listDir({path:e}={},t={}){try{const r=e||baseDir(t),o=fs.readdirSync(r,{withFileTypes:!0}).filter((e=>!IGNORED_DIRS.has(e.name))).map((e=>e.isDirectory()?`${e.name}/`:e.name)).sort(((e,t)=>e.localeCompare(t)));return ok(o.join("\n")||"(empty directory)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function globToRegex(e){let t="^";for(let r=0;r<e.length;r++){const o=e[r];"*"===o?"*"===e[r+1]?(t+=".*",r++):t+="[^/]*":"?"===o?t+="[^/]":/[.+^${}()|[\]\\]/.test(o)?t+=`\\${o}`:t+=o}return new RegExp(t+"$")}function walk(e,t,r=0){if(r>12)return;let o;try{o=fs.readdirSync(e,{withFileTypes:!0})}catch{return}for(const i of o){if(IGNORED_DIRS.has(i.name))continue;const o=path.join(e,i.name);i.isDirectory()?walk(o,t,r+1):t(o)}}function glob({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const o=t||baseDir(r),i=globToRegex(String(e)),n=[];return walk(o,(e=>{if(n.length>=100)return;const t=path.relative(o,e).split(path.sep).join("/");i.test(t)&&n.push(t)})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function grep({pattern:e,path:t}={},r={}){try{if(!e)return fail("pattern is required");const o=new RegExp(e),i=t||baseDir(r),n=[];return walk(i,(e=>{if(n.length>=100)return;let t;try{if(fs.statSync(e).size>10485760)return;t=fs.readFileSync(e,"utf8")}catch{return}const r=path.relative(i,e).split(path.sep).join("/");for(const[e,i]of t.split("\n").entries()){if(n.length>=100)return;o.test(i)&&n.push(`${r}:${e+1}: ${i.slice(0,160)}`)}})),ok(n.join("\n")||"(no matches)")}catch(e){return fail(e&&e.message?e.message:String(e))}}function execOneShot({command:e,cwd:t,timeout:r,maxBuffer:o}={}){return new Promise((i=>{const n=Math.min(Number(o)||EXEC_MAX_BUFFER,EXEC_MAX_BUFFER),s=Math.min(Number(r)||EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP),a=shells.oneShotShellSpec();if(!a.ok)return void i(fail(a.error));const{cmd:l,arg:c}=a;let d;try{d=spawn(l,[c,e],{cwd:t||process.cwd(),timeout:s,killSignal:"SIGKILL",windowsHide:!0})}catch(e){return void i(fail(`spawn failed: ${e&&e.message?e.message:e}`))}let u="",p=0,h=!1,f=!1,g=!1;const m=setTimeout((()=>{f=!0;try{d.kill("SIGKILL")}catch{}}),s),k=e=>{if(p+=e.length,p>n){h=!0;try{d.kill("SIGKILL")}catch{}}else u+=e};d.stdout&&d.stdout.on("data",k),d.stderr&&d.stderr.on("data",k);const y=e=>{g||(g=!0,clearTimeout(m),i(e))};d.on("error",(e=>y(fail(`spawn failed: ${e&&e.message?e.message:e}`)))),d.on("close",((e,t)=>{const r=u.trim();if(f)return void y(fail(`command timed out after ${s}ms${r?`\n${r}`:""}`));if(h)return void y(fail(`output exceeded ${n} bytes and was truncated\n${r}`));const o=`exit ${null==e?`signal ${t}`:e}`;y(0===e?ok(r||`(${o}, no output)`):fail(`${o}${r?`\n${r}`:""}`))}))}))}function execInShell(e,{command:t,cwd:r,timeout:o},i){return i&&i.aborted?(e.dispose(),Promise.resolve(fail("aborted"))):new Promise((n=>{const s=()=>e.dispose();i&&i.addEventListener("abort",s,{once:!0});const a=()=>{i&&i.removeEventListener("abort",s)};e.run(t,{timeout:o,working_directory:r}).then((e=>{a(),n(e.isError?fail(e.content):ok(e.content))}),(e=>{a(),n(fail(`shell session failed: ${e&&e.message?e.message:e}`))}))}))}function exec({command:e,cwd:t,timeout:r,maxBuffer:o}={},i={}){if(!e||"string"!=typeof e)return Promise.resolve(fail("command is required"));const n="function"==typeof i.getShell?i.getShell():null;return n?execInShell(n,{command:e,cwd:t,timeout:r},i.signal):execOneShot({command:e,cwd:t,timeout:r,maxBuffer:o})}let hooksLib=null;try{hooksLib=require("../../../client/hooks.js")}catch{try{hooksLib=require("../../vendor/hooks.js")}catch{hooksLib=null}}const HOOKS_LIB_MISSING="the shared hook module could not be loaded (tried client/hooks.js beside the app and vendor/hooks.js inside it) — run scripts/predist.mjs before packaging.";function hooksListing(e){const t=[],r=e&&e.hooks?e.hooks:{};for(const[e,o]of Object.entries(r)){t.push(`${e} (${o.length})`);for(const e of o){if(!e)continue;t.push(` - ${e.name||"(unnamed)"}`);const r=e.matcher;r&&r.tools&&t.push(` tools: ${r.tools}`),r&&r.paths&&t.push(` paths: ${r.paths}`),r&&r.commands&&t.push(` commands: ${r.commands}`)}}return t.length?t.join("\n"):"(no hooks declared in any settings file)"}function hooks({sub:e,cwd:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);try{const r={cwd:t||process.cwd()},o=hooksLib.readHookConfig(r);if("list"===String(e||"status").toLowerCase())return ok(hooksListing(o));const i=hooksLib.hookStats(o.hooks);return ok(hooksLib.hooksSummary({...r,config:o,stats:i}))}catch(e){return fail(e&&e.message?e.message:String(e))}}function installHooks({cwd:e,dry_run:t}={}){if(!hooksLib)return fail(HOOKS_LIB_MISSING);let r;try{r=hooksLib.installRepoHooks({cwd:e||process.cwd(),dryRun:Boolean(t)})}catch(e){return fail(e&&e.message?e.message:String(e))}const o=r.actions.length?`\n ${r.actions.join("\n ")}`:"";return r.ok?t?ok(`would install the guard hooks in ${r.status.repo}${o||"\n (already installed — nothing to do)"}`+(r.status.installed?"":"\n re-run without dry_run to apply")):r.changed?ok(`guard hooks installed in ${r.status.repo}\n core.hooksPath = .githooks (verified by reading it back)${o}\n ${r.status.execNote}\n a commit and a push in this tree are now gated.`):ok(`guard hooks already installed in ${r.status.repo}: core.hooksPath = .githooks\n ${r.status.execNote}`):fail(`${r.error}${o}`)}const EXECUTORS={readFile:readFile,writeFile:writeFile,editFile:editFile,listDir:listDir,glob:glob,grep:grep,exec:exec,hooks:hooks,installHooks:installHooks};function isTool(e){return Object.prototype.hasOwnProperty.call(EXECUTORS,e)}let agentGatePromise;function agentGateCandidates({resourcesPath:e=process.resourcesPath,dirname:t=__dirname}={}){const r=["../../../tools/agent-gate.mjs"];return"string"==typeof e&&e&&r.push(pathToFileURL(path.join(e,"tools","agent-gate.mjs")).href),r.push("../../vendor/agent-gate.mjs"),r}function loadAgentGate(){if(!agentGatePromise){const e=agentGateCandidates(),t=r=>r>=e.length?null:import(e[r]).catch((()=>t(r+1)));agentGatePromise=t(0)}return agentGatePromise}function nearestManifest(e){let t=path.resolve(e||process.cwd());try{fs.statSync(t).isFile()&&(t=path.dirname(t))}catch{}for(;;){const e=path.join(t,".aegis","guard.json");if(fs.existsSync(e))return e;const r=path.dirname(t);if(r===t)return null;t=r}}async function executeTool(e,t,r){if(!isTool(e))return fail(`unknown tool "${e}" (known: ${toolNames().join(", ")})`);const o=normalizeArgs(e,t,r||{});if(!o.ok)return fail(o.error);const i=o.args;let n=null;try{n=await loadAgentGate()}catch{}if(n){const t=n.guardTool({tool:e,args:i,cwd:r&&r.cwd||process.cwd(),env:process.env,unattended:Boolean(r&&r.autonomous)});if(!t.allowed)return fail(n.refusalText(t));if("skipped"===t.code){const o=await EXECUTORS[e](i,r||{});return o&&"object"==typeof o?{...o,output:`⚠ ${t.reason}\n${o.output||""}`}:o}}else if(MUTATING_TOOLS.has(e)){const t=nearestManifest(r&&r.cwd||process.cwd());if(t)return fail(`error: refused — ${t} declares an agent-gated tree, but the agent-key gate module could not be loaded (tried tools/agent-gate.mjs beside the app and vendor/agent-gate.mjs inside it), so this ${e} cannot be authorised. A build that missed the staged copy is the usual cause: run scripts/predist.mjs before packaging.`)}try{return await EXECUTORS[e](i,r||{})}catch(e){return fail(e&&e.message?e.message:String(e))}}function toolResultText(e){return e?e.ok?String(null==e.output?"":e.output):`error: ${e.error}`:"error: tool produced no result"}module.exports={SCHEMAS:SCHEMAS,SUBAGENT_TOOL:SUBAGENT_TOOL,HOOK_TOOLS:HOOK_TOOLS,toolNames:toolNames,openaiTools:openaiTools,toolsFor:toolsFor,executeTool:executeTool,isTool:isTool,toolResultText:toolResultText,MUTATING_TOOLS:MUTATING_TOOLS,previewMutation:previewMutation,applyChecked:applyChecked,normalizeArgs:normalizeArgs,TOOL_PATH_ARGS:TOOL_PATH_ARGS,PATH_ARG_DESC:PATH_ARG_DESC,OUTPUT_CAP:3e4,READ_LINE_CAP:2e3,MATCH_CAP:100,READ_SIZE_CAP:26214400,GREP_SIZE_CAP:10485760,EXEC_TIMEOUT_DEFAULT:EXEC_TIMEOUT_DEFAULT,EXEC_TIMEOUT_CAP:EXEC_TIMEOUT_CAP,EXEC_MAX_BUFFER:EXEC_MAX_BUFFER,DIFF_MAX_CELLS:DIFF_MAX_CELLS,DIFF_MAX_LINES:DIFF_MAX_LINES};