@muyichengshayu/promptx 0.2.7 → 0.2.8

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 (43) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/apps/runner/src/engines/claudeCodeRunner.js +69 -1
  3. package/apps/runner/src/engines/claudeCodeRunner.test.js +279 -0
  4. package/apps/runner/src/engines/openCodeRunner.test.js +73 -0
  5. package/apps/runner/src/engines/shellRunner.test.js +46 -0
  6. package/apps/runner/src/runManager.js +110 -11
  7. package/apps/runner/src/runManager.test.js +913 -0
  8. package/apps/runner/src/serverClient.test.js +93 -0
  9. package/apps/server/src/agentSessionDiscovery.test.js +127 -0
  10. package/apps/server/src/agents/claudeCodeRunner.test.js +433 -0
  11. package/apps/server/src/agents/openCodeRunner.test.js +236 -0
  12. package/apps/server/src/agents/runnerContract.test.js +382 -0
  13. package/apps/server/src/appPaths.test.js +52 -0
  14. package/apps/server/src/assetRoutes.test.js +168 -0
  15. package/apps/server/src/codex.test.js +518 -0
  16. package/apps/server/src/codexRoutes.test.js +376 -0
  17. package/apps/server/src/codexRuns.test.js +160 -0
  18. package/apps/server/src/codexSessions.test.js +369 -0
  19. package/apps/server/src/db.test.js +182 -0
  20. package/apps/server/src/gitDiff.test.js +542 -0
  21. package/apps/server/src/gitDiffClient.test.js +140 -0
  22. package/apps/server/src/internalRoutes.test.js +134 -0
  23. package/apps/server/src/maintenance.test.js +154 -0
  24. package/apps/server/src/processControl.test.js +147 -0
  25. package/apps/server/src/relayClient.test.js +478 -0
  26. package/apps/server/src/relayConfig.test.js +73 -0
  27. package/apps/server/src/relayProtocol.test.js +49 -0
  28. package/apps/server/src/relayServer.test.js +798 -0
  29. package/apps/server/src/relayTenants.test.js +137 -0
  30. package/apps/server/src/relayUsageStore.test.js +65 -0
  31. package/apps/server/src/repository.test.js +150 -0
  32. package/apps/server/src/runDispatchService.test.js +563 -0
  33. package/apps/server/src/runEventIngest.test.js +225 -0
  34. package/apps/server/src/runRecovery.test.js +73 -0
  35. package/apps/server/src/runnerClient.test.js +80 -0
  36. package/apps/server/src/runnerDispatch.test.js +136 -0
  37. package/apps/server/src/systemConfig.test.js +112 -0
  38. package/apps/server/src/systemRoutes.test.js +319 -0
  39. package/apps/server/src/taskRoutes.test.js +726 -0
  40. package/apps/server/src/upload.test.js +30 -0
  41. package/apps/server/src/webAppRoutes.test.js +67 -0
  42. package/apps/server/src/workspaceFiles.test.js +262 -0
  43. package/package.json +14 -21
@@ -0,0 +1,236 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import {
5
+ createOpenCodeNormalizationState,
6
+ extractOpenCodeErrorMessage,
7
+ extractOpenCodeSessionId,
8
+ extractOpenCodeText,
9
+ extractOpenCodeUsage,
10
+ normalizeOpenCodeEvent,
11
+ normalizeOpenCodeEvents,
12
+ } from './openCodeRunner.js'
13
+
14
+ test('extractOpenCodeSessionId reads common session id fields', () => {
15
+ assert.equal(extractOpenCodeSessionId({ sessionID: 'opencode-session-1' }), 'opencode-session-1')
16
+ assert.equal(extractOpenCodeSessionId({ sessionId: 'opencode-session-2' }), 'opencode-session-2')
17
+ })
18
+
19
+ test('extractOpenCodeText trims text payload', () => {
20
+ assert.equal(
21
+ extractOpenCodeText({
22
+ type: 'text',
23
+ part: {
24
+ type: 'text',
25
+ text: '\n\n已完成修改\n',
26
+ },
27
+ }),
28
+ '已完成修改'
29
+ )
30
+ })
31
+
32
+ test('normalizeOpenCodeEvent maps text output to agent message', () => {
33
+ assert.deepEqual(
34
+ normalizeOpenCodeEvent({
35
+ type: 'text',
36
+ part: {
37
+ type: 'text',
38
+ text: '已完成修改',
39
+ },
40
+ }),
41
+ {
42
+ type: 'item.completed',
43
+ item: {
44
+ type: 'agent_message',
45
+ text: '已完成修改',
46
+ },
47
+ }
48
+ )
49
+ })
50
+
51
+ test('normalizeOpenCodeEvents maps first step_start to turn.started only once', () => {
52
+ const state = createOpenCodeNormalizationState()
53
+
54
+ assert.deepEqual(
55
+ normalizeOpenCodeEvents({
56
+ type: 'step_start',
57
+ sessionID: 'ses_1',
58
+ }, state),
59
+ [{ type: 'turn.started' }]
60
+ )
61
+
62
+ assert.deepEqual(
63
+ normalizeOpenCodeEvents({
64
+ type: 'step_start',
65
+ sessionID: 'ses_1',
66
+ }, state),
67
+ []
68
+ )
69
+ })
70
+
71
+ test('normalizeOpenCodeEvents maps completed tool_use to command events', () => {
72
+ assert.deepEqual(
73
+ normalizeOpenCodeEvents({
74
+ type: 'tool_use',
75
+ sessionID: 'ses_2',
76
+ part: {
77
+ type: 'tool',
78
+ tool: 'read',
79
+ state: {
80
+ status: 'completed',
81
+ input: {
82
+ filePath: '/tmp/demo.txt',
83
+ },
84
+ output: '<path>/tmp/demo.txt</path>',
85
+ },
86
+ },
87
+ }),
88
+ [
89
+ {
90
+ type: 'item.started',
91
+ item: {
92
+ type: 'command_execution',
93
+ command: 'read: /tmp/demo.txt',
94
+ status: 'in_progress',
95
+ },
96
+ },
97
+ {
98
+ type: 'item.completed',
99
+ item: {
100
+ type: 'command_execution',
101
+ command: 'read: /tmp/demo.txt',
102
+ status: 'completed',
103
+ exit_code: 0,
104
+ aggregated_output: '<path>/tmp/demo.txt</path>',
105
+ },
106
+ },
107
+ ]
108
+ )
109
+ })
110
+
111
+ test('normalizeOpenCodeEvent maps step_finish stop to turn completion with usage', () => {
112
+ const event = normalizeOpenCodeEvent({
113
+ type: 'step_finish',
114
+ part: {
115
+ type: 'step-finish',
116
+ reason: 'stop',
117
+ tokens: {
118
+ input: 321,
119
+ output: 12,
120
+ cache: {
121
+ read: 256,
122
+ },
123
+ },
124
+ },
125
+ })
126
+
127
+ assert.deepEqual(event, {
128
+ type: 'turn.completed',
129
+ usage: {
130
+ input_tokens: 321,
131
+ output_tokens: 12,
132
+ cached_input_tokens: 256,
133
+ },
134
+ })
135
+
136
+ assert.deepEqual(extractOpenCodeUsage({
137
+ part: {
138
+ tokens: {
139
+ input: 321,
140
+ output: 12,
141
+ cache: {
142
+ read: 256,
143
+ },
144
+ },
145
+ },
146
+ }), {
147
+ input_tokens: 321,
148
+ output_tokens: 12,
149
+ cached_input_tokens: 256,
150
+ })
151
+ })
152
+
153
+ test('extractOpenCodeErrorMessage reads nested API errors', () => {
154
+ assert.equal(
155
+ extractOpenCodeErrorMessage({
156
+ type: 'error',
157
+ error: {
158
+ name: 'APIError',
159
+ data: {
160
+ message: 'openai_error',
161
+ responseBody: '{"error":{"message":"bad gateway"}}',
162
+ },
163
+ },
164
+ }),
165
+ 'openai_error'
166
+ )
167
+ })
168
+
169
+ test('normalizeOpenCodeEvents maps sub-agent task tool_use to collaboration events', () => {
170
+ assert.deepEqual(
171
+ normalizeOpenCodeEvents({
172
+ type: 'tool_use',
173
+ sessionID: 'ses_main',
174
+ part: {
175
+ type: 'tool',
176
+ tool: 'task',
177
+ state: {
178
+ status: 'completed',
179
+ input: {
180
+ description: '分析 a.js 文件',
181
+ prompt: '请分析 /tmp/demo/a.js 文件',
182
+ subagent_type: 'explore',
183
+ },
184
+ output: 'task_id: ses_child_1\n\n<task_result>ok</task_result>',
185
+ metadata: {
186
+ sessionId: 'ses_child_1',
187
+ model: {
188
+ providerID: 'opencode',
189
+ modelID: 'minimax-m2.5-free',
190
+ },
191
+ },
192
+ },
193
+ },
194
+ }),
195
+ [
196
+ {
197
+ type: 'item.completed',
198
+ item: {
199
+ type: 'collab_tool_call',
200
+ tool: 'spawn_agent',
201
+ receiver_thread_ids: ['ses_child_1'],
202
+ prompt: '请分析 /tmp/demo/a.js 文件',
203
+ agents_states: {
204
+ ses_child_1: {
205
+ status: 'completed',
206
+ message: 'task_id: ses_child_1\n\n<task_result>ok</task_result>',
207
+ title: '分析 a.js 文件',
208
+ role: 'explore',
209
+ target: 'a.js',
210
+ model: 'opencode/minimax-m2.5-free',
211
+ },
212
+ },
213
+ },
214
+ },
215
+ {
216
+ type: 'item.completed',
217
+ item: {
218
+ type: 'collab_tool_call',
219
+ tool: 'wait',
220
+ receiver_thread_ids: ['ses_child_1'],
221
+ prompt: '请分析 /tmp/demo/a.js 文件',
222
+ agents_states: {
223
+ ses_child_1: {
224
+ status: 'completed',
225
+ message: 'task_id: ses_child_1\n\n<task_result>ok</task_result>',
226
+ title: '分析 a.js 文件',
227
+ role: 'explore',
228
+ target: 'a.js',
229
+ model: 'opencode/minimax-m2.5-free',
230
+ },
231
+ },
232
+ },
233
+ },
234
+ ]
235
+ )
236
+ })
@@ -0,0 +1,382 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import test from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+
7
+ function withEnv(overrides, fn) {
8
+ const previous = new Map()
9
+
10
+ for (const [key, value] of Object.entries(overrides)) {
11
+ previous.set(key, process.env[key])
12
+ if (typeof value === 'undefined') {
13
+ delete process.env[key]
14
+ } else {
15
+ process.env[key] = value
16
+ }
17
+ }
18
+
19
+ return Promise.resolve()
20
+ .then(fn)
21
+ .finally(() => {
22
+ for (const [key, value] of previous.entries()) {
23
+ if (typeof value === 'undefined') {
24
+ delete process.env[key]
25
+ } else {
26
+ process.env[key] = value
27
+ }
28
+ }
29
+ })
30
+ }
31
+
32
+ async function importFreshRunnerModules() {
33
+ const suffix = `test=${Date.now()}-${Math.random().toString(16).slice(2)}`
34
+ const [
35
+ { streamPromptToCodexSession },
36
+ { streamPromptToClaudeCodeSession },
37
+ { streamPromptToOpenCodeSession },
38
+ ] = await Promise.all([
39
+ import(`../codex.js?${suffix}`),
40
+ import(`./claudeCodeRunner.js?${suffix}`),
41
+ import(`./openCodeRunner.js?${suffix}`),
42
+ ])
43
+
44
+ return {
45
+ streamPromptToCodexSession,
46
+ streamPromptToClaudeCodeSession,
47
+ streamPromptToOpenCodeSession,
48
+ }
49
+ }
50
+
51
+ function createFakeCodexBinary(tempDir) {
52
+ const scriptPath = path.join(tempDir, process.platform === 'win32' ? 'fake-codex.js' : 'fake-codex')
53
+ const script = `#!/usr/bin/env node
54
+ const fs = require('node:fs')
55
+
56
+ const args = process.argv.slice(2)
57
+ const outputIndex = args.indexOf('--output-last-message')
58
+ const outputFile = outputIndex >= 0 ? args[outputIndex + 1] : ''
59
+ const threadId = 'thread-contract-1'
60
+
61
+ let prompt = ''
62
+ process.stdin.setEncoding('utf8')
63
+ process.stdin.on('data', (chunk) => {
64
+ prompt += chunk
65
+ })
66
+ process.stdin.on('end', () => {
67
+ if (outputFile) {
68
+ fs.writeFileSync(outputFile, '最终回复')
69
+ }
70
+
71
+ process.stdout.write(JSON.stringify({ type: 'thread.started', thread_id: threadId }) + '\\n')
72
+ process.stdout.write(JSON.stringify({ type: 'item.started', item: { type: 'reasoning', text: '先分析' } }) + '\\n')
73
+ process.stdout.write(JSON.stringify({ type: 'item.started', item: { type: 'command_execution', command: 'Bash: pwd', status: 'in_progress' } }) + '\\n')
74
+ process.stdout.write(JSON.stringify({ type: 'item.completed', item: { type: 'command_execution', command: 'Bash: pwd', status: 'completed', exit_code: 0, aggregated_output: '/tmp/demo' } }) + '\\n')
75
+ process.stdout.write(JSON.stringify({ type: 'item.completed', item: { type: 'agent_message', text: '已完成修改' } }) + '\\n')
76
+ process.stdout.write(JSON.stringify({ type: 'turn.completed', result: '最终回复' }) + '\\n')
77
+ })
78
+ `
79
+
80
+ fs.writeFileSync(scriptPath, script, { mode: 0o755 })
81
+
82
+ if (process.platform !== 'win32') {
83
+ return scriptPath
84
+ }
85
+
86
+ const cmdPath = path.join(tempDir, 'fake-codex.cmd')
87
+ fs.writeFileSync(cmdPath, '@echo off\r\nnode "%~dp0fake-codex.js" %*\r\n')
88
+ return cmdPath
89
+ }
90
+
91
+ function createFakeClaudeBinary(tempDir) {
92
+ const scriptPath = path.join(tempDir, process.platform === 'win32' ? 'fake-claude.js' : 'fake-claude')
93
+ const script = `#!/usr/bin/env node
94
+ const args = process.argv.slice(2)
95
+ const promptIndex = args.indexOf('-p')
96
+ const prompt = promptIndex >= 0 ? args[promptIndex + 1] || '' : ''
97
+ const resumeIndex = args.indexOf('--resume')
98
+ const threadId = resumeIndex >= 0 ? args[resumeIndex + 1] || 'thread-contract-1' : 'thread-contract-1'
99
+
100
+ if (!prompt) {
101
+ process.stderr.write('missing prompt\\n')
102
+ process.exit(1)
103
+ return
104
+ }
105
+
106
+ process.stdout.write(JSON.stringify({
107
+ type: 'system',
108
+ subtype: 'init',
109
+ session_id: threadId,
110
+ }) + '\\n')
111
+
112
+ process.stdout.write(JSON.stringify({
113
+ type: 'assistant',
114
+ message: {
115
+ content: [
116
+ { type: 'thinking', thinking: '先分析' },
117
+ { type: 'tool_use', id: 'tool-1', name: 'Bash', input: { command: 'pwd' } },
118
+ ],
119
+ },
120
+ }) + '\\n')
121
+
122
+ process.stdout.write(JSON.stringify({
123
+ type: 'user',
124
+ message: {
125
+ content: [
126
+ { type: 'tool_result', tool_use_id: 'tool-1', content: '/tmp/demo', is_error: false },
127
+ ],
128
+ },
129
+ }) + '\\n')
130
+
131
+ process.stdout.write(JSON.stringify({
132
+ type: 'assistant',
133
+ message: {
134
+ content: [
135
+ { type: 'text', text: '已完成修改' },
136
+ ],
137
+ },
138
+ }) + '\\n')
139
+
140
+ process.stdout.write(JSON.stringify({
141
+ type: 'result',
142
+ result: '最终回复',
143
+ }) + '\\n')
144
+ `
145
+
146
+ fs.writeFileSync(scriptPath, script, { mode: 0o755 })
147
+
148
+ if (process.platform !== 'win32') {
149
+ return scriptPath
150
+ }
151
+
152
+ const cmdPath = path.join(tempDir, 'fake-claude.cmd')
153
+ fs.writeFileSync(cmdPath, '@echo off\r\nnode "%~dp0fake-claude.js" %*\r\n')
154
+ return cmdPath
155
+ }
156
+
157
+ function createFakeOpenCodeBinary(tempDir) {
158
+ const scriptPath = path.join(tempDir, process.platform === 'win32' ? 'fake-opencode.js' : 'fake-opencode')
159
+ const script = `#!/usr/bin/env node
160
+ const args = process.argv.slice(2)
161
+ const sessionIndex = args.indexOf('--session')
162
+ const sessionId = sessionIndex >= 0 ? args[sessionIndex + 1] || 'thread-contract-1' : 'thread-contract-1'
163
+ const prompt = args[args.length - 1] || ''
164
+
165
+ if (!prompt) {
166
+ process.stderr.write('missing prompt\\n')
167
+ process.exit(1)
168
+ return
169
+ }
170
+
171
+ process.stdout.write(JSON.stringify({
172
+ type: 'step_start',
173
+ sessionID: sessionId,
174
+ part: {
175
+ type: 'step-start',
176
+ },
177
+ }) + '\\n')
178
+
179
+ process.stdout.write(JSON.stringify({
180
+ type: 'tool_use',
181
+ sessionID: sessionId,
182
+ part: {
183
+ type: 'tool',
184
+ tool: 'read',
185
+ state: {
186
+ status: 'completed',
187
+ input: {
188
+ filePath: '/tmp/demo',
189
+ },
190
+ output: 'demo output',
191
+ },
192
+ },
193
+ }) + '\\n')
194
+
195
+ process.stdout.write(JSON.stringify({
196
+ type: 'text',
197
+ sessionID: sessionId,
198
+ part: {
199
+ type: 'text',
200
+ text: '最终回复',
201
+ },
202
+ }) + '\\n')
203
+
204
+ process.stdout.write(JSON.stringify({
205
+ type: 'step_finish',
206
+ sessionID: sessionId,
207
+ part: {
208
+ type: 'step-finish',
209
+ reason: 'stop',
210
+ tokens: {
211
+ input: 100,
212
+ output: 20,
213
+ cache: {
214
+ read: 10,
215
+ },
216
+ },
217
+ },
218
+ }) + '\\n')
219
+ `
220
+
221
+ fs.writeFileSync(scriptPath, script, { mode: 0o755 })
222
+
223
+ if (process.platform !== 'win32') {
224
+ return scriptPath
225
+ }
226
+
227
+ const cmdPath = path.join(tempDir, 'fake-opencode.cmd')
228
+ fs.writeFileSync(cmdPath, '@echo off\r\nnode "%~dp0fake-opencode.js" %*\r\n')
229
+ return cmdPath
230
+ }
231
+
232
+ function simplifyEvent(event = {}) {
233
+ if (event.type === 'status') {
234
+ return {
235
+ type: 'status',
236
+ stage: event.stage,
237
+ message: event.message,
238
+ }
239
+ }
240
+
241
+ if (event.type === 'completed') {
242
+ return {
243
+ type: 'completed',
244
+ message: event.message,
245
+ }
246
+ }
247
+
248
+ if (event.type !== 'agent_event') {
249
+ return { type: event.type }
250
+ }
251
+
252
+ return {
253
+ type: 'agent_event',
254
+ event: event.event,
255
+ }
256
+ }
257
+
258
+ async function collectRunnerContractEvents(streamSessionPrompt) {
259
+ const events = []
260
+ const stream = streamSessionPrompt(
261
+ { id: 'session-1', cwd: process.cwd() },
262
+ 'runner-contract-case',
263
+ {
264
+ onEvent(event) {
265
+ events.push(simplifyEvent(event))
266
+ },
267
+ }
268
+ )
269
+
270
+ const result = await stream.result
271
+ return {
272
+ events,
273
+ result,
274
+ }
275
+ }
276
+
277
+ function projectRunnerContractPhases(events = []) {
278
+ return events.map((event) => {
279
+ if (event.type === 'status') {
280
+ return 'status'
281
+ }
282
+
283
+ if (event.type === 'completed') {
284
+ return 'completed'
285
+ }
286
+
287
+ if (event.type !== 'agent_event') {
288
+ return ''
289
+ }
290
+
291
+ const payload = event.event || {}
292
+ if (payload.type === 'thread.started') {
293
+ return 'thread.started'
294
+ }
295
+
296
+ if (payload.type === 'turn.started') {
297
+ return 'turn.started'
298
+ }
299
+
300
+ if (payload.type === 'item.started' && payload.item?.type === 'command_execution') {
301
+ return 'command.started'
302
+ }
303
+
304
+ if (payload.type === 'item.completed' && payload.item?.type === 'command_execution') {
305
+ return 'command.completed'
306
+ }
307
+
308
+ if (payload.type === 'item.completed' && payload.item?.type === 'agent_message') {
309
+ return 'agent_message'
310
+ }
311
+
312
+ if (payload.type === 'turn.completed') {
313
+ return 'turn.completed'
314
+ }
315
+
316
+ return ''
317
+ }).filter(Boolean)
318
+ }
319
+
320
+ function assertOrderedSubsequence(actual = [], expected = []) {
321
+ let actualIndex = 0
322
+
323
+ expected.forEach((item) => {
324
+ while (actualIndex < actual.length && actual[actualIndex] !== item) {
325
+ actualIndex += 1
326
+ }
327
+
328
+ assert.ok(actualIndex < actual.length, `未找到预期阶段:${item},实际阶段:${actual.join(' -> ')}`)
329
+ actualIndex += 1
330
+ })
331
+ }
332
+
333
+ function assertRunnerContract(result, expectedThreadId) {
334
+ assert.deepEqual(result.result, {
335
+ sessionId: 'session-1',
336
+ threadId: expectedThreadId,
337
+ message: '最终回复',
338
+ })
339
+
340
+ const phases = projectRunnerContractPhases(result.events)
341
+ assertOrderedSubsequence(phases, [
342
+ 'status',
343
+ 'thread.started',
344
+ 'command.started',
345
+ 'command.completed',
346
+ 'agent_message',
347
+ 'turn.completed',
348
+ 'completed',
349
+ ])
350
+ }
351
+
352
+ test('Codex / Claude Code / OpenCode runner 会产出兼容的核心事件结构', async () => {
353
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'promptx-runner-contract-'))
354
+ const fakeCodexBin = createFakeCodexBinary(tempDir)
355
+ const fakeClaudeBin = createFakeClaudeBinary(tempDir)
356
+ const fakeOpenCodeBin = createFakeOpenCodeBinary(tempDir)
357
+
358
+ await withEnv(
359
+ {
360
+ CODEX_BIN: fakeCodexBin,
361
+ CLAUDE_CODE_BIN: fakeClaudeBin,
362
+ OPENCODE_BIN: fakeOpenCodeBin,
363
+ },
364
+ async () => {
365
+ const {
366
+ streamPromptToCodexSession,
367
+ streamPromptToClaudeCodeSession,
368
+ streamPromptToOpenCodeSession,
369
+ } = await importFreshRunnerModules()
370
+
371
+ const [codexResult, claudeResult, openCodeResult] = await Promise.all([
372
+ collectRunnerContractEvents(streamPromptToCodexSession),
373
+ collectRunnerContractEvents(streamPromptToClaudeCodeSession),
374
+ collectRunnerContractEvents(streamPromptToOpenCodeSession),
375
+ ])
376
+
377
+ assertRunnerContract(codexResult, 'thread-contract-1')
378
+ assertRunnerContract(claudeResult, 'thread-contract-1')
379
+ assertRunnerContract(openCodeResult, 'thread-contract-1')
380
+ }
381
+ )
382
+ })
@@ -0,0 +1,52 @@
1
+ import assert from 'node:assert/strict'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import test from 'node:test'
6
+
7
+ function withEnv(overrides, fn) {
8
+ const previous = new Map()
9
+
10
+ for (const [key, value] of Object.entries(overrides)) {
11
+ previous.set(key, process.env[key])
12
+ if (typeof value === 'undefined') {
13
+ delete process.env[key]
14
+ } else {
15
+ process.env[key] = value
16
+ }
17
+ }
18
+
19
+ return Promise.resolve()
20
+ .then(fn)
21
+ .finally(() => {
22
+ for (const [key, value] of previous.entries()) {
23
+ if (typeof value === 'undefined') {
24
+ delete process.env[key]
25
+ } else {
26
+ process.env[key] = value
27
+ }
28
+ }
29
+ })
30
+ }
31
+
32
+ test('appPaths resolves storage under PROMPTX_HOME by default', async () => {
33
+ const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), 'promptx-home-'))
34
+
35
+ await withEnv(
36
+ {
37
+ PROMPTX_HOME: tempHome,
38
+ PROMPTX_DATA_DIR: undefined,
39
+ PROMPTX_UPLOADS_DIR: undefined,
40
+ PROMPTX_TMP_DIR: undefined,
41
+ },
42
+ async () => {
43
+ const appPaths = await import(`./appPaths.js?test=${Date.now()}`)
44
+ const resolved = appPaths.ensurePromptxStorageReady()
45
+
46
+ assert.equal(resolved.promptxHomeDir, tempHome)
47
+ assert.equal(resolved.dataDir, path.join(tempHome, 'data'))
48
+ assert.equal(resolved.uploadsDir, path.join(tempHome, 'uploads'))
49
+ assert.equal(resolved.tmpDir, path.join(tempHome, 'tmp'))
50
+ }
51
+ )
52
+ })