@gotgenes/pi-permission-system 18.1.1 → 18.2.0

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 (133) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/docs/configuration.md +11 -0
  3. package/package.json +1 -2
  4. package/src/access-intent/access-path.ts +29 -4
  5. package/src/access-intent/bash/bash-path-resolver.ts +39 -18
  6. package/src/access-intent/bash/msys-bash-tokens.ts +64 -0
  7. package/src/extension-config.ts +7 -0
  8. package/src/forwarded-permissions/permission-forwarder.ts +6 -3
  9. package/src/handlers/gates/helpers.ts +1 -1
  10. package/src/handlers/gates/runner.ts +22 -0
  11. package/src/index.ts +10 -6
  12. package/src/path-normalizer.ts +105 -2
  13. package/src/permission-manager.ts +21 -1
  14. package/src/permission-prompter.ts +10 -16
  15. package/src/prompting-gateway.ts +13 -17
  16. package/src/rule.ts +21 -1
  17. package/src/status.ts +1 -1
  18. package/src/yolo-mode.ts +0 -30
  19. package/test/access-intent/access-path.test.ts +0 -277
  20. package/test/access-intent/bash/node-text.test.ts +0 -148
  21. package/test/access-intent/bash/parser.test.ts +0 -19
  22. package/test/access-intent/bash/program.test.ts +0 -673
  23. package/test/access-intent/bash/token-classification.test.ts +0 -363
  24. package/test/access-intent/bash/token-collection.test.ts +0 -300
  25. package/test/active-agent.test.ts +0 -155
  26. package/test/async-cache.test.ts +0 -48
  27. package/test/bash-arity.test.ts +0 -144
  28. package/test/bash-external-directory.test.ts +0 -1022
  29. package/test/builtin-tool-input-formatters.test.ts +0 -109
  30. package/test/canonicalize-path.test.ts +0 -119
  31. package/test/composition-root.test.ts +0 -698
  32. package/test/config-loader.test.ts +0 -740
  33. package/test/config-modal.test.ts +0 -320
  34. package/test/config-paths.test.ts +0 -83
  35. package/test/config-pipeline.test.ts +0 -90
  36. package/test/config-reporter.test.ts +0 -147
  37. package/test/config-store.test.ts +0 -466
  38. package/test/decision-audit.test.ts +0 -72
  39. package/test/decision-reporter.test.ts +0 -112
  40. package/test/denial-messages.test.ts +0 -714
  41. package/test/detect-permissive-bash-fallback.test.ts +0 -56
  42. package/test/expand-home.test.ts +0 -93
  43. package/test/extension-config.test.ts +0 -129
  44. package/test/extension-paths.test.ts +0 -108
  45. package/test/forwarded-permissions/io.test.ts +0 -251
  46. package/test/forwarding-manager.test.ts +0 -200
  47. package/test/handlers/before-agent-start.test.ts +0 -314
  48. package/test/handlers/external-directory-integration.test.ts +0 -515
  49. package/test/handlers/external-directory-session-dedup.test.ts +0 -175
  50. package/test/handlers/external-directory-symlink-acceptance.test.ts +0 -167
  51. package/test/handlers/gates/bash-command-metamorphic.test.ts +0 -88
  52. package/test/handlers/gates/bash-command.test.ts +0 -257
  53. package/test/handlers/gates/bash-external-directory.test.ts +0 -268
  54. package/test/handlers/gates/bash-path.test.ts +0 -346
  55. package/test/handlers/gates/candidate-check.test.ts +0 -52
  56. package/test/handlers/gates/external-directory-messages.test.ts +0 -85
  57. package/test/handlers/gates/external-directory-policy.test.ts +0 -134
  58. package/test/handlers/gates/external-directory.test.ts +0 -267
  59. package/test/handlers/gates/helpers.test.ts +0 -165
  60. package/test/handlers/gates/path.test.ts +0 -369
  61. package/test/handlers/gates/runner.test.ts +0 -408
  62. package/test/handlers/gates/skill-input-gate-pipeline.test.ts +0 -176
  63. package/test/handlers/gates/skill-input.test.ts +0 -128
  64. package/test/handlers/gates/skill-read.test.ts +0 -161
  65. package/test/handlers/gates/tool-call-gate-pipeline.test.ts +0 -356
  66. package/test/handlers/gates/tool.test.ts +0 -244
  67. package/test/handlers/input-events.test.ts +0 -168
  68. package/test/handlers/input.test.ts +0 -199
  69. package/test/handlers/lifecycle.test.ts +0 -221
  70. package/test/handlers/tool-call-boundary.test.ts +0 -145
  71. package/test/handlers/tool-call-events.test.ts +0 -277
  72. package/test/handlers/tool-call.test.ts +0 -395
  73. package/test/handlers/validate-requested-tool.test.ts +0 -92
  74. package/test/helpers/external-directory-fixtures.ts +0 -269
  75. package/test/helpers/gate-fixtures.ts +0 -316
  76. package/test/helpers/handler-fixtures.ts +0 -335
  77. package/test/helpers/make-fake-pi.ts +0 -100
  78. package/test/helpers/manager-harness.ts +0 -112
  79. package/test/helpers/session-fixtures.ts +0 -199
  80. package/test/input-normalizer.test.ts +0 -325
  81. package/test/logging.test.ts +0 -51
  82. package/test/mcp-targets.test.ts +0 -233
  83. package/test/node-modules-discovery.test.ts +0 -97
  84. package/test/normalize.test.ts +0 -247
  85. package/test/path-containment.test.ts +0 -161
  86. package/test/path-normalization.test.ts +0 -233
  87. package/test/path-normalizer.test.ts +0 -196
  88. package/test/path-surfaces.test.ts +0 -55
  89. package/test/pattern-suggest.test.ts +0 -248
  90. package/test/permission-dialog.test.ts +0 -205
  91. package/test/permission-event-rpc.test.ts +0 -560
  92. package/test/permission-events.test.ts +0 -400
  93. package/test/permission-forwarder.test.ts +0 -370
  94. package/test/permission-forwarding.test.ts +0 -315
  95. package/test/permission-gate.test.ts +0 -269
  96. package/test/permission-manager-unified.test.ts +0 -3714
  97. package/test/permission-merge.test.ts +0 -61
  98. package/test/permission-prompter.test.ts +0 -518
  99. package/test/permission-prompts.test.ts +0 -363
  100. package/test/permission-resolver.test.ts +0 -277
  101. package/test/permission-session.test.ts +0 -404
  102. package/test/permission-ui-prompt.test.ts +0 -146
  103. package/test/permissions-service.test.ts +0 -192
  104. package/test/pi-infrastructure-read.test.ts +0 -432
  105. package/test/policy-loader.test.ts +0 -561
  106. package/test/prompting-gateway.test.ts +0 -231
  107. package/test/rule.test.ts +0 -650
  108. package/test/safe-system-paths.test.ts +0 -46
  109. package/test/scope-merge.test.ts +0 -116
  110. package/test/service-lifecycle.test.ts +0 -163
  111. package/test/service.test.ts +0 -261
  112. package/test/session-approval.test.ts +0 -75
  113. package/test/session-logger.test.ts +0 -200
  114. package/test/session-rules.test.ts +0 -321
  115. package/test/session-start.test.ts +0 -112
  116. package/test/skill-prompt-sanitizer.test.ts +0 -418
  117. package/test/status.test.ts +0 -10
  118. package/test/subagent-context.test.ts +0 -372
  119. package/test/subagent-lifecycle-events.test.ts +0 -132
  120. package/test/subagent-registry.test.ts +0 -145
  121. package/test/synthesize.test.ts +0 -302
  122. package/test/system-prompt-sanitizer.test.ts +0 -382
  123. package/test/tool-access-extractor-registry.test.ts +0 -77
  124. package/test/tool-input-formatter-registry.test.ts +0 -75
  125. package/test/tool-input-path.test.ts +0 -84
  126. package/test/tool-input-preview.test.ts +0 -129
  127. package/test/tool-input-prompt-formatters.test.ts +0 -115
  128. package/test/tool-preview-formatter.test.ts +0 -458
  129. package/test/tool-registry.test.ts +0 -197
  130. package/test/value-guards.test.ts +0 -193
  131. package/test/wildcard-matcher.test.ts +0 -424
  132. package/test/yaml-frontmatter.test.ts +0 -91
  133. package/test/yolo-mode.test.ts +0 -188
@@ -1,200 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
-
3
- import { ForwardingManager } from "#src/forwarding-manager";
4
-
5
- // ── Mocks ─────────────────────────────────────────────────────────────────
6
-
7
- const mockProcessInbox = vi.hoisted(() =>
8
- vi.fn((): Promise<void> => Promise.resolve()),
9
- );
10
- const mockIsSubagentExecutionContext = vi.hoisted(() => vi.fn());
11
-
12
- vi.mock("../src/subagent-context", () => ({
13
- isSubagentExecutionContext: mockIsSubagentExecutionContext,
14
- }));
15
-
16
- // ── Helpers ───────────────────────────────────────────────────────────────
17
-
18
- function makeCtx(overrides: { hasUI?: boolean; sessionId?: string } = {}) {
19
- return {
20
- hasUI: overrides.hasUI ?? true,
21
- sessionManager: {
22
- getSessionId: vi.fn().mockReturnValue(overrides.sessionId ?? "sess-1"),
23
- },
24
- cwd: "/project",
25
- } as unknown as import("@earendil-works/pi-coding-agent").ExtensionContext;
26
- }
27
-
28
- function makeForwarder() {
29
- return { processInbox: mockProcessInbox };
30
- }
31
-
32
- function makeManager() {
33
- return new ForwardingManager(
34
- "/agent/subagent-sessions",
35
- makeForwarder(),
36
- "linux",
37
- );
38
- }
39
-
40
- // ── Tests ─────────────────────────────────────────────────────────────────
41
-
42
- describe("ForwardingManager", () => {
43
- beforeEach(() => {
44
- vi.useFakeTimers();
45
- mockIsSubagentExecutionContext.mockReset();
46
- mockIsSubagentExecutionContext.mockReturnValue(false);
47
- mockProcessInbox.mockReset();
48
- mockProcessInbox.mockResolvedValue(undefined);
49
- });
50
-
51
- afterEach(() => {
52
- vi.useRealTimers();
53
- });
54
-
55
- describe("stop()", () => {
56
- it("is a no-op when not started", () => {
57
- const manager = makeManager();
58
- expect(() => manager.stop()).not.toThrow();
59
- });
60
-
61
- it("clears the timer and processing state after start()", async () => {
62
- const manager = makeManager();
63
- const ctx = makeCtx();
64
- manager.start(ctx);
65
- manager.stop();
66
-
67
- // After stop, the timer fires no more callbacks.
68
- mockProcessInbox.mockClear();
69
- await vi.advanceTimersByTimeAsync(500);
70
- expect(mockProcessInbox).not.toHaveBeenCalled();
71
- });
72
- });
73
-
74
- describe("start()", () => {
75
- it("does not start polling when hasUI is false", async () => {
76
- const manager = makeManager();
77
- const ctx = makeCtx({ hasUI: false });
78
- manager.start(ctx);
79
-
80
- await vi.advanceTimersByTimeAsync(500);
81
- expect(mockProcessInbox).not.toHaveBeenCalled();
82
- });
83
-
84
- it("stops any existing poll and does not start a new one when hasUI is false", async () => {
85
- const manager = makeManager();
86
- const uiCtx = makeCtx({ hasUI: true });
87
- const noUiCtx = makeCtx({ hasUI: false });
88
-
89
- manager.start(uiCtx);
90
- // Now stop the polling by calling start() with no-UI ctx.
91
- manager.start(noUiCtx);
92
-
93
- mockProcessInbox.mockClear();
94
- await vi.advanceTimersByTimeAsync(500);
95
- expect(mockProcessInbox).not.toHaveBeenCalled();
96
- });
97
-
98
- it("does not start polling when isSubagentExecutionContext returns true", async () => {
99
- mockIsSubagentExecutionContext.mockReturnValue(true);
100
- const manager = makeManager();
101
- const ctx = makeCtx();
102
- manager.start(ctx);
103
-
104
- await vi.advanceTimersByTimeAsync(500);
105
- expect(mockProcessInbox).not.toHaveBeenCalled();
106
- });
107
-
108
- it("stops any existing poll when called with a subagent context", async () => {
109
- mockIsSubagentExecutionContext.mockReturnValueOnce(false);
110
- const manager = makeManager();
111
- const ctx1 = makeCtx();
112
- manager.start(ctx1);
113
-
114
- // Second call with a subagent context.
115
- mockIsSubagentExecutionContext.mockReturnValue(true);
116
- const ctx2 = makeCtx();
117
- manager.start(ctx2);
118
-
119
- mockProcessInbox.mockClear();
120
- await vi.advanceTimersByTimeAsync(500);
121
- expect(mockProcessInbox).not.toHaveBeenCalled();
122
- });
123
-
124
- it("starts polling and calls processInbox on tick", async () => {
125
- const manager = makeManager();
126
- const ctx = makeCtx();
127
- manager.start(ctx);
128
-
129
- await vi.advanceTimersByTimeAsync(250);
130
- expect(mockProcessInbox).toHaveBeenCalledWith(ctx);
131
- });
132
-
133
- it("is idempotent — calling start() twice does not create a second timer", async () => {
134
- const manager = makeManager();
135
- const ctx = makeCtx();
136
- manager.start(ctx);
137
- manager.start(ctx);
138
-
139
- await vi.advanceTimersByTimeAsync(250);
140
- // Only one tick should fire per interval, not two.
141
- expect(mockProcessInbox).toHaveBeenCalledTimes(1);
142
- });
143
-
144
- it("updates the context when called again while already running", async () => {
145
- const manager = makeManager();
146
- const ctx1 = makeCtx({ sessionId: "sess-1" });
147
- const ctx2 = makeCtx({ sessionId: "sess-2" });
148
- manager.start(ctx1);
149
- manager.start(ctx2);
150
-
151
- await vi.advanceTimersByTimeAsync(250);
152
- // The process call should use the newer context.
153
- expect(mockProcessInbox).toHaveBeenCalledWith(ctx2);
154
- });
155
-
156
- it("skips a tick while processing is in progress", async () => {
157
- // Make processInbox hang so processing=true persists.
158
- let resolveProcess: () => void;
159
- mockProcessInbox.mockReturnValue(
160
- new Promise<void>((resolve) => {
161
- resolveProcess = resolve;
162
- }),
163
- );
164
-
165
- const manager = makeManager();
166
- const ctx = makeCtx();
167
- manager.start(ctx);
168
-
169
- // First tick starts processing.
170
- await vi.advanceTimersByTimeAsync(250);
171
- expect(mockProcessInbox).toHaveBeenCalledTimes(1);
172
-
173
- // Second tick is skipped because processing flag is still true.
174
- await vi.advanceTimersByTimeAsync(250);
175
- expect(mockProcessInbox).toHaveBeenCalledTimes(1);
176
-
177
- // Resolve and a third tick should fire.
178
- resolveProcess!();
179
- await vi.advanceTimersByTimeAsync(250);
180
- expect(mockProcessInbox).toHaveBeenCalledTimes(2);
181
- });
182
-
183
- it("passes subagentSessionsDir from the constructor to isSubagentExecutionContext", () => {
184
- const manager = new ForwardingManager(
185
- "/custom/subagent-dir",
186
- makeForwarder(),
187
- "linux",
188
- );
189
- const ctx = makeCtx();
190
- manager.start(ctx);
191
-
192
- expect(mockIsSubagentExecutionContext).toHaveBeenCalledWith(
193
- ctx,
194
- "/custom/subagent-dir",
195
- "linux",
196
- undefined,
197
- );
198
- });
199
- });
200
- });
@@ -1,314 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
-
3
- import {
4
- AgentPrepHandler,
5
- shouldExposeTool,
6
- } from "#src/handlers/before-agent-start";
7
- import type { ToolRegistry } from "#src/tool-registry";
8
-
9
- import { makeCheckResult, makeCtx } from "#test/helpers/handler-fixtures";
10
- import {
11
- makeRealResolver,
12
- makeRealSession,
13
- } from "#test/helpers/session-fixtures";
14
-
15
- // ── SDK stubs ──────────────────────────────────────────────────────────────
16
- vi.mock("@earendil-works/pi-coding-agent", async (importOriginal) => {
17
- const original =
18
- await importOriginal<typeof import("@earendil-works/pi-coding-agent")>();
19
- return {
20
- ...original,
21
- isToolCallEventType: vi.fn().mockReturnValue(false),
22
- };
23
- });
24
-
25
- // ── helpers ────────────────────────────────────────────────────────────────
26
-
27
- function makeEvent(systemPrompt = "You are an assistant.") {
28
- return { systemPrompt };
29
- }
30
-
31
- function makeToolRegistry(overrides: Partial<ToolRegistry> = {}): ToolRegistry {
32
- return {
33
- getAll: vi.fn().mockReturnValue([]),
34
- getActive: vi.fn().mockReturnValue([]),
35
- setActive: vi.fn(),
36
- ...overrides,
37
- };
38
- }
39
-
40
- function makeSetup(opts?: {
41
- toolPermission?: "allow" | "deny" | "ask";
42
- toolRegistry?: Partial<ToolRegistry>;
43
- }) {
44
- const { session, permissionManager, sessionRules, configStore, forwarding } =
45
- makeRealSession();
46
- const { resolver } = makeRealResolver(permissionManager, sessionRules);
47
- if (opts?.toolPermission !== undefined) {
48
- vi.mocked(permissionManager.getToolPermission).mockReturnValue(
49
- opts.toolPermission,
50
- );
51
- }
52
- // Default check returns allow (for skill-prompt sanitizer via resolver.checkPermission)
53
- vi.mocked(permissionManager.check).mockReturnValue(makeCheckResult());
54
- const toolRegistry = makeToolRegistry(opts?.toolRegistry);
55
- const handler = new AgentPrepHandler(session, resolver, toolRegistry);
56
- return {
57
- handler,
58
- session,
59
- resolver,
60
- permissionManager,
61
- configStore,
62
- forwarding,
63
- toolRegistry,
64
- };
65
- }
66
-
67
- // ── shouldExposeTool (pure helper) ─────────────────────────────────────────
68
-
69
- describe("shouldExposeTool", () => {
70
- it("returns true when tool permission is allow", () => {
71
- const getter = vi.fn().mockReturnValue("allow");
72
- expect(shouldExposeTool("read", null, getter)).toBe(true);
73
- });
74
-
75
- it("returns true when tool permission is ask", () => {
76
- const getter = vi.fn().mockReturnValue("ask");
77
- expect(shouldExposeTool("bash", "agent-x", getter)).toBe(true);
78
- });
79
-
80
- it("returns false when tool permission is deny", () => {
81
- const getter = vi.fn().mockReturnValue("deny");
82
- expect(shouldExposeTool("write", null, getter)).toBe(false);
83
- });
84
-
85
- it("passes agentName through to getToolPermission", () => {
86
- const getter = vi.fn().mockReturnValue("allow");
87
- shouldExposeTool("read", "my-agent", getter);
88
- expect(getter).toHaveBeenCalledWith("read", "my-agent");
89
- });
90
-
91
- it("converts null agentName to undefined for getToolPermission", () => {
92
- const getter = vi.fn().mockReturnValue("allow");
93
- shouldExposeTool("read", null, getter);
94
- expect(getter).toHaveBeenCalledWith("read", undefined);
95
- });
96
- });
97
-
98
- // ── AgentPrepHandler.handle ────────────────────────────────────────────────
99
-
100
- describe("AgentPrepHandler.handle", () => {
101
- it("activates the session with ctx", async () => {
102
- const ctx = makeCtx();
103
- const { handler, forwarding } = makeSetup();
104
- await handler.handle(makeEvent(), ctx);
105
- // Real session.activate calls forwarding.start
106
- expect(forwarding.start).toHaveBeenCalledWith(ctx);
107
- });
108
-
109
- it("refreshes config with ctx", async () => {
110
- const ctx = makeCtx();
111
- const { handler, configStore } = makeSetup();
112
- await handler.handle(makeEvent(), ctx);
113
- expect(configStore.refresh).toHaveBeenCalledWith(ctx);
114
- });
115
-
116
- it("resolves agent name using systemPrompt", async () => {
117
- const ctx = makeCtx();
118
- const { handler, session } = makeSetup();
119
- const spy = vi.spyOn(session, "resolveAgentName");
120
- await handler.handle(makeEvent("<active_agent name='x'>"), ctx);
121
- expect(spy).toHaveBeenCalledWith(ctx, "<active_agent name='x'>");
122
- });
123
-
124
- it("filters out denied tools from allowed list", async () => {
125
- const { handler, toolRegistry } = makeSetup({
126
- toolPermission: "deny",
127
- toolRegistry: {
128
- getActive: vi.fn().mockReturnValue(["write", "read"]),
129
- },
130
- });
131
- await handler.handle(makeEvent(), makeCtx());
132
- expect(toolRegistry.setActive).toHaveBeenCalledWith([]);
133
- });
134
-
135
- it("includes allowed and ask tools in the active list", async () => {
136
- const { handler, toolRegistry } = makeSetup({
137
- toolRegistry: {
138
- getActive: vi.fn().mockReturnValue(["read", "write"]),
139
- },
140
- });
141
- await handler.handle(makeEvent(), makeCtx());
142
- expect(toolRegistry.setActive).toHaveBeenCalledWith(["read", "write"]);
143
- });
144
-
145
- it("does not activate registered tools pi left inactive (find/grep/ls)", async () => {
146
- // Regression for #385: the active set is the base, not the full registry.
147
- const { handler, toolRegistry } = makeSetup({
148
- toolRegistry: {
149
- getActive: vi.fn().mockReturnValue(["read", "bash", "edit", "write"]),
150
- getAll: vi
151
- .fn()
152
- .mockReturnValue([
153
- { name: "read" },
154
- { name: "bash" },
155
- { name: "edit" },
156
- { name: "write" },
157
- { name: "find" },
158
- { name: "grep" },
159
- { name: "ls" },
160
- ]),
161
- },
162
- });
163
- await handler.handle(makeEvent(), makeCtx());
164
- expect(toolRegistry.setActive).toHaveBeenCalledWith([
165
- "read",
166
- "bash",
167
- "edit",
168
- "write",
169
- ]);
170
- });
171
-
172
- it("calls setActive on every turn (no dedup gate)", async () => {
173
- const { handler, toolRegistry } = makeSetup({
174
- toolRegistry: {
175
- getActive: vi.fn().mockReturnValue(["read"]),
176
- },
177
- });
178
- await handler.handle(makeEvent(), makeCtx());
179
- await handler.handle(makeEvent(), makeCtx());
180
- expect(toolRegistry.setActive).toHaveBeenCalledTimes(2);
181
- });
182
-
183
- it("filters a denied skill from the systemPrompt on every turn, not just the first", async () => {
184
- const systemPrompt = [
185
- "You are an assistant.",
186
- "",
187
- "<available_skills>",
188
- " <skill>",
189
- " <name>secret</name>",
190
- " <description>A denied skill</description>",
191
- " <location>/skills/secret/SKILL.md</location>",
192
- " </skill>",
193
- "</available_skills>",
194
- ].join("\n");
195
- const { handler, permissionManager } = makeSetup();
196
- vi.mocked(permissionManager.check).mockImplementation((intent) =>
197
- intent.surface === "skill"
198
- ? makeCheckResult({ state: "deny" })
199
- : makeCheckResult(),
200
- );
201
-
202
- const first = await handler.handle(makeEvent(systemPrompt), makeCtx());
203
- const second = await handler.handle(makeEvent(systemPrompt), makeCtx());
204
-
205
- expect(first).toHaveProperty("systemPrompt");
206
- expect((first as { systemPrompt: string }).systemPrompt).not.toContain(
207
- "secret",
208
- );
209
- expect(second).toHaveProperty("systemPrompt");
210
- expect((second as { systemPrompt: string }).systemPrompt).not.toContain(
211
- "secret",
212
- );
213
- });
214
-
215
- it("returns empty object on repeated calls with unchanged inputs", async () => {
216
- const { handler } = makeSetup();
217
- await handler.handle(makeEvent(), makeCtx());
218
- const result = await handler.handle(makeEvent(), makeCtx());
219
- expect(result).toEqual({});
220
- });
221
-
222
- it("stores resolved skill entries on the session", async () => {
223
- const { handler, session } = makeSetup();
224
- const spy = vi.spyOn(session, "setActiveSkillEntries");
225
- await handler.handle(makeEvent(), makeCtx());
226
- expect(spy).toHaveBeenCalledWith(expect.any(Array));
227
- });
228
-
229
- it("returns modified systemPrompt when prompt changes", async () => {
230
- const systemPrompt = `You are an assistant.\n\nAvailable tools:\n- read\n- write\n`;
231
- const { handler } = makeSetup();
232
- const result = await handler.handle(makeEvent(systemPrompt), makeCtx());
233
- expect(result).toHaveProperty("systemPrompt");
234
- });
235
-
236
- it("returns empty object when systemPrompt is unchanged", async () => {
237
- const prompt = "No tools section here.";
238
- const { handler } = makeSetup();
239
- const result = await handler.handle(makeEvent(prompt), makeCtx());
240
- expect(result).toEqual({});
241
- });
242
-
243
- it("narrows a denied tool out of the Available tools listing without removing the section", async () => {
244
- const systemPrompt = [
245
- "Available tools:",
246
- "- read: Read file contents",
247
- "- bash: Run shell commands",
248
- ].join("\n");
249
- const { handler, permissionManager } = makeSetup({
250
- toolRegistry: {
251
- getActive: vi.fn().mockReturnValue(["read", "bash"]),
252
- },
253
- });
254
- vi.mocked(permissionManager.getToolPermission).mockImplementation((tool) =>
255
- tool === "bash" ? "deny" : "allow",
256
- );
257
-
258
- const result = await handler.handle(makeEvent(systemPrompt), makeCtx());
259
-
260
- expect(result.systemPrompt).toBeDefined();
261
- const out = result.systemPrompt ?? "";
262
- expect(out).toContain("Available tools:");
263
- expect(out).toContain("- read: Read file contents");
264
- expect(out).not.toContain("- bash");
265
- });
266
-
267
- it("keeps the wire system prompt byte-stable across the tool-listing drift between turns", async () => {
268
- const fullProse = [
269
- "You are an assistant.",
270
- "",
271
- "Available tools:",
272
- "- bash: Run shell commands",
273
- "- read: Read file contents",
274
- "- edit: Edit a file",
275
- "- write: Write a file",
276
- "",
277
- "Guidelines:",
278
- "- use bash for file operations like ls, rg, find",
279
- "- use read to examine files instead of cat or sed.",
280
- "- Be concise in your responses",
281
- ].join("\n");
282
- const narrowedProse = [
283
- "You are an assistant.",
284
- "",
285
- "Available tools:",
286
- "- read: Read file contents",
287
- "- edit: Edit a file",
288
- "- write: Write a file",
289
- "",
290
- "Guidelines:",
291
- "- use read to examine files instead of cat or sed.",
292
- "- Be concise in your responses",
293
- ].join("\n");
294
- const { handler, permissionManager } = makeSetup({
295
- toolRegistry: {
296
- getActive: vi.fn().mockReturnValue(["bash", "read", "edit", "write"]),
297
- },
298
- });
299
- vi.mocked(permissionManager.getToolPermission).mockImplementation((tool) =>
300
- tool === "bash" ? "deny" : "allow",
301
- );
302
-
303
- // Turn 1: Pi feeds the full default listing.
304
- const first = await handler.handle(makeEvent(fullProse), makeCtx());
305
- // Turn 2: Pi's setActive rebuild means the event now carries the narrowed
306
- // listing, so the override the handler returns must still match turn 1.
307
- const second = await handler.handle(makeEvent(narrowedProse), makeCtx());
308
-
309
- const wire1 = first.systemPrompt ?? fullProse;
310
- const wire2 = second.systemPrompt ?? narrowedProse;
311
- expect(wire1).toBe(narrowedProse);
312
- expect(wire2).toBe(narrowedProse);
313
- });
314
- });