@causyne/agent 1.20.121 → 1.20.122

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 (256) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -12,8 +12,10 @@ function withUsageLock<T>(fn: () => Promise<T>): Promise<T> {
12
12
  return run;
13
13
  }
14
14
 
15
+ let usageTempCounter = 0;
15
16
  function writeUsageFile(file: string, payload: unknown): void {
16
- const temp = `${file}.tmp_${process.pid}`;
17
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
18
+ const temp = `${file}.tmp_${process.pid}_${++usageTempCounter}`;
17
19
  fs.writeFileSync(temp, JSON.stringify(payload, null, 2), { encoding: 'utf8', mode: 0o600 });
18
20
  fs.renameSync(temp, file);
19
21
  }
@@ -209,19 +211,24 @@ export class TokenTracker {
209
211
  }
210
212
 
211
213
  calculateCost(promptTokens: number, completionTokens: number, usageDetail: UsageDetail | null = null): number {
212
- const [promptPrice, completionPrice] = this.getPricing(promptTokens);
213
-
214
- const cachedTokens = Math.min(Number(usageDetail?.cachedPromptTokens || 0), promptTokens);
215
- const writeTokens = Math.min(Number(usageDetail?.cacheWriteTokens || 0), promptTokens - cachedTokens);
216
- const fullPriceTokens = Math.max(0, promptTokens - cachedTokens - writeTokens);
217
-
218
- const writeMultiplier = Number(usageDetail?.cacheWriteMultiplier || 1.25);
214
+ const safePrompt = Number.isFinite(promptTokens) ? Math.max(0, Number(promptTokens)) : 0;
215
+ const safeCompletion = Number.isFinite(completionTokens) ? Math.max(0, Number(completionTokens)) : 0;
216
+ const [promptPrice, completionPrice] = this.getPricing(safePrompt);
217
+
218
+ const rawCached = Number(usageDetail?.cachedPromptTokens ?? 0);
219
+ const cachedTokens = Math.min(Number.isFinite(rawCached) ? Math.max(0, rawCached) : 0, safePrompt);
220
+ const rawWrite = Number(usageDetail?.cacheWriteTokens ?? 0);
221
+ const writeTokens = Math.min(Number.isFinite(rawWrite) ? Math.max(0, rawWrite) : 0, safePrompt - cachedTokens);
222
+ const fullPriceTokens = Math.max(0, safePrompt - cachedTokens - writeTokens);
223
+
224
+ const rawMult = Number(usageDetail?.cacheWriteMultiplier ?? 1.25);
225
+ const writeMultiplier = Number.isFinite(rawMult) && rawMult >= 0 ? rawMult : 1.25;
219
226
  const promptCost =
220
227
  (fullPriceTokens / 1_000_000) * promptPrice +
221
228
  (cachedTokens / 1_000_000) * promptPrice * this.cachedInputMultiplier() +
222
229
  (writeTokens / 1_000_000) * promptPrice * writeMultiplier;
223
230
 
224
- const completionCost = (completionTokens / 1_000_000) * completionPrice;
231
+ const completionCost = (safeCompletion / 1_000_000) * completionPrice;
225
232
  return promptCost + completionCost;
226
233
  }
227
234
 
@@ -269,7 +276,8 @@ export class TokenTracker {
269
276
  this.applyEnforcedTaskLimit();
270
277
 
271
278
  const unitPrice = this.getMediaPricing(provider, model, mediaType);
272
- const cost = unitPrice * (quantityUnits || 1);
279
+ const safeUnits = Number.isFinite(quantityUnits) ? Math.max(0, Number(quantityUnits)) : 1;
280
+ const cost = unitPrice * safeUnits;
273
281
 
274
282
  const equivalentTokens = Math.round(cost / 0.000002);
275
283
 
@@ -278,17 +286,20 @@ export class TokenTracker {
278
286
  this.taskCostUsd += cost;
279
287
  this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
280
288
 
281
- const cumulative = await this.getCumulativeUsage();
282
- const daily = await this.getDailyUsage();
283
- daily.totalTokens += equivalentTokens;
284
- daily.totalCalls += 1;
285
- daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
286
- await this.saveDailyUsage(daily);
289
+ const { daily } = await withUsageLock(async () => {
290
+ const cumulative = await this.getCumulativeUsage();
291
+ const daily = await this.getDailyUsage();
292
+ daily.totalTokens += equivalentTokens;
293
+ daily.totalCalls += 1;
294
+ daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
295
+ await this.saveDailyUsage(daily);
287
296
 
288
- cumulative.totalTokens += equivalentTokens;
289
- cumulative.totalCalls += 1;
290
- cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
291
- await this.saveCumulativeUsage(cumulative);
297
+ cumulative.totalTokens += equivalentTokens;
298
+ cumulative.totalCalls += 1;
299
+ cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
300
+ await this.saveCumulativeUsage(cumulative);
301
+ return { daily };
302
+ });
292
303
 
293
304
  if (!this.budget.enabled) {
294
305
  return { allowed: true, used: daily.totalTokens, costUsd: daily.totalCostUsd, taskCostUsd: this.taskCostUsd, equivalentTokens };
@@ -406,17 +417,15 @@ export class TokenTracker {
406
417
  }
407
418
 
408
419
  async resetDailyUsage(): Promise<void> {
409
- const file = this.getDailyFile();
410
- if (fs.existsSync(file)) {
411
- fs.unlinkSync(file);
412
- }
420
+ await withUsageLock(async () => {
421
+ fs.rmSync(this.getDailyFile(), { force: true });
422
+ });
413
423
  }
414
424
 
415
425
  async resetCumulativeUsage(): Promise<void> {
416
- const file = this.getCumulativeFile();
417
- if (fs.existsSync(file)) {
418
- fs.unlinkSync(file);
419
- }
426
+ await withUsageLock(async () => {
427
+ fs.rmSync(this.getCumulativeFile(), { force: true });
428
+ });
420
429
  }
421
430
 
422
431
  async getReportedUsage(): Promise<{
@@ -467,10 +476,15 @@ export class TokenTracker {
467
476
  }
468
477
 
469
478
  extendBudget(extraTokens: number): void {
479
+ if (!Number.isFinite(extraTokens) || extraTokens <= 0) return;
470
480
  if (this.budget && typeof this.budget === 'object') {
471
481
  const current = Number(this.budget.maxTokensPerTask || 0);
472
482
  if (current > 0) {
473
- this.budget.maxTokensPerTask = Math.max(current + extraTokens, this.taskTokens + extraTokens);
483
+ const next = Math.max(current + extraTokens, this.taskTokens + extraTokens);
484
+ this.budget.maxTokensPerTask = next;
485
+ if (this.enforcedTaskTokenLimit !== null) {
486
+ this.enforcedTaskTokenLimit = Math.floor(next);
487
+ }
474
488
  }
475
489
  }
476
490
  }
@@ -567,7 +581,7 @@ export class TokenTracker {
567
581
  this.sessionTokens = (this.sessionTokens || 0) + freshStep;
568
582
  this.largestStepTokens = Math.max(this.largestStepTokens || 0, freshStep);
569
583
 
570
- const cost = this.calculateCost(promptTokens, completionTokens, usageDetail);
584
+ const cost = this.calculateCost(pTokens, cTokens, usageDetail);
571
585
  this.taskCostUsd += cost;
572
586
  this.sessionCostUsd = (this.sessionCostUsd || 0) + cost;
573
587
 
package/src/toolPacks.js CHANGED
@@ -377,7 +377,9 @@ export function routePacks(prompt, workspaceContext = null) {
377
377
  for (const packName of PACK_NAMES) {
378
378
  const matched = packName === 'reverse_engineering'
379
379
  ? isReverseEngineeringIntent(text)
380
- : INTENT_MATCHERS[packName].test(text);
380
+ : packName === 'web'
381
+ ? isWebIntent(text)
382
+ : INTENT_MATCHERS[packName].test(text);
381
383
  if (matched) {
382
384
  unlocked.add(packName);
383
385
  }
package/src/toolPacks.ts CHANGED
@@ -431,7 +431,9 @@ export function routePacks(
431
431
  for (const packName of PACK_NAMES) {
432
432
  const matched = packName === 'reverse_engineering'
433
433
  ? isReverseEngineeringIntent(text)
434
- : INTENT_MATCHERS[packName].test(text);
434
+ : packName === 'web'
435
+ ? isWebIntent(text)
436
+ : INTENT_MATCHERS[packName].test(text);
435
437
  if (matched) {
436
438
  unlocked.add(packName);
437
439
  }
@@ -1,9 +1,69 @@
1
1
  import fs from 'node:fs/promises';
2
- import { existsSync, statSync, createWriteStream } from 'node:fs';
2
+ import { existsSync, lstatSync, realpathSync, statSync, createWriteStream } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { resolveUserPath } from '../utils/paths.js';
6
6
  import { loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
7
+ function expandArchivePath(raw, baseRoot) {
8
+ const trimmed = raw.trim();
9
+ if (trimmed === '~' || trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
10
+ return resolveUserPath(trimmed);
11
+ }
12
+ if (path.isAbsolute(trimmed))
13
+ return path.resolve(trimmed);
14
+ return path.resolve(baseRoot ? resolveUserPath(baseRoot) : process.cwd(), trimmed);
15
+ }
16
+ function canonicalArchivePath(target) {
17
+ const resolved = path.resolve(target);
18
+ try {
19
+ return realpathSync(resolved);
20
+ }
21
+ catch {
22
+ let current = resolved;
23
+ const missing = [];
24
+ for (let i = 0; i < 64; i++) {
25
+ const parent = path.dirname(current);
26
+ if (parent === current)
27
+ break;
28
+ missing.unshift(path.basename(current));
29
+ current = parent;
30
+ try {
31
+ return path.join(realpathSync(current), ...missing);
32
+ }
33
+ catch {
34
+ continue;
35
+ }
36
+ }
37
+ return resolved;
38
+ }
39
+ }
40
+ function assertArchiveScope(target, context) {
41
+ if (!context || context.grantAllAccess === true)
42
+ return;
43
+ const configured = Array.isArray(context.workspacePaths)
44
+ ? context.workspacePaths.filter((p) => typeof p === 'string' && p.trim().length > 0).map(p => p.trim())
45
+ : [];
46
+ const roots = configured.length > 0
47
+ ? configured
48
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
49
+ .filter((p) => typeof p === 'string' && p.trim().length > 0)
50
+ .map(p => p.trim());
51
+ if (roots.length === 0)
52
+ return;
53
+ const physical = canonicalArchivePath(target);
54
+ for (const root of roots) {
55
+ try {
56
+ const realRoot = realpathSync(resolveUserPath(root));
57
+ const rel = path.relative(realRoot, physical);
58
+ if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)))
59
+ return;
60
+ }
61
+ catch {
62
+ continue;
63
+ }
64
+ }
65
+ throw new Error(`Archive path resolves outside the selected workspace: ${target}`);
66
+ }
7
67
  export const archive = {
8
68
  schema: {
9
69
  name: 'archive',
@@ -18,16 +78,32 @@ export const archive = {
18
78
  required: ['action', 'source', 'destination']
19
79
  }
20
80
  },
21
- async execute(args) {
81
+ async execute(args, context) {
22
82
  try {
23
- if (!args || !args.action || !args.source || !args.destination) {
83
+ if (!args || typeof args !== 'object' || typeof args.action !== 'string' || typeof args.source !== 'string' || typeof args.destination !== 'string' || !args.source.trim() || !args.destination.trim()) {
24
84
  return { success: false, error: 'Missing required arguments: action, source, destination' };
25
85
  }
26
- const source = resolveUserPath(args.source);
27
- const dest = resolveUserPath(args.destination);
86
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
87
+ || context?.workspaceRoot?.trim()
88
+ || context?.workspacePaths?.find((p) => typeof p === 'string' && p.trim().length > 0)?.trim();
89
+ const isHomeOrAbs = (val) => {
90
+ const trimmed = val.trim();
91
+ return trimmed === '~' || trimmed.startsWith('~/') || trimmed.startsWith('~\\') || path.isAbsolute(trimmed);
92
+ };
93
+ const source = (!baseRoot || isHomeOrAbs(args.source))
94
+ ? resolveUserPath(args.source)
95
+ : expandArchivePath(args.source, baseRoot);
96
+ const dest = (!baseRoot || isHomeOrAbs(args.destination))
97
+ ? resolveUserPath(args.destination)
98
+ : expandArchivePath(args.destination, baseRoot);
99
+ assertArchiveScope(source, context);
100
+ assertArchiveScope(dest, context);
28
101
  if (!existsSync(source)) {
29
102
  return { success: false, error: `Archive source path not found: ${source}` };
30
103
  }
104
+ if (existsSync(dest) && lstatSync(dest).isSymbolicLink()) {
105
+ return { success: false, error: `Refusing to write through symbolic link destination: ${dest}` };
106
+ }
31
107
  if (args.action === 'extract') {
32
108
  return await extractArchive(source, dest);
33
109
  }
@@ -43,6 +119,65 @@ export const archive = {
43
119
  }
44
120
  }
45
121
  };
122
+ function isUnsafeArchiveMemberName(member) {
123
+ const normalized = member.replace(/\\/g, '/').trim();
124
+ if (!normalized)
125
+ return true;
126
+ if (normalized.startsWith('/') || /^[a-zA-Z]:/.test(normalized))
127
+ return true;
128
+ return normalized.split('/').some(seg => seg === '..');
129
+ }
130
+ function precheckNativeZipEntries(source) {
131
+ const listing = execFileSync('unzip', ['-Z', '-s', source], {
132
+ stdio: 'pipe',
133
+ encoding: 'utf8',
134
+ timeout: 15_000,
135
+ maxBuffer: 10 * 1024 * 1024,
136
+ windowsHide: true
137
+ });
138
+ for (const line of listing.split('\n')) {
139
+ const trimmed = line.trim();
140
+ if (!trimmed || trimmed.startsWith('Archive:') || trimmed.startsWith('Zip file size:') || /^\d+\s+files?,/.test(trimmed))
141
+ continue;
142
+ if (/^l/.test(trimmed)) {
143
+ throw new Error(`Refusing symlink entry inside zip archive: ${trimmed}`);
144
+ }
145
+ const parts = trimmed.split(/\s+/);
146
+ const name = parts.slice(8).join(' ');
147
+ if (name && isUnsafeArchiveMemberName(name)) {
148
+ throw new Error(`Refusing unsafe zip archive path traversal entry: ${name}`);
149
+ }
150
+ }
151
+ }
152
+ function precheckNativeTarEntries(source) {
153
+ const listing = execFileSync('tar', ['-tvf', source], {
154
+ stdio: 'pipe',
155
+ encoding: 'utf8',
156
+ timeout: 15_000,
157
+ maxBuffer: 10 * 1024 * 1024,
158
+ windowsHide: true
159
+ });
160
+ for (const line of listing.split('\n')) {
161
+ const trimmed = line.trim();
162
+ if (!trimmed)
163
+ continue;
164
+ if (/^[lhbcp]/.test(trimmed) || trimmed.includes(' -> ')) {
165
+ throw new Error(`Refusing symlink or special device entry inside tar archive: ${trimmed}`);
166
+ }
167
+ }
168
+ const names = execFileSync('tar', ['-tf', source], {
169
+ stdio: 'pipe',
170
+ encoding: 'utf8',
171
+ timeout: 15_000,
172
+ maxBuffer: 10 * 1024 * 1024,
173
+ windowsHide: true
174
+ });
175
+ for (const name of names.split('\n')) {
176
+ if (name.trim() && isUnsafeArchiveMemberName(name)) {
177
+ throw new Error(`Refusing unsafe tar archive path traversal entry: ${name}`);
178
+ }
179
+ }
180
+ }
46
181
  async function extractArchive(source, dest) {
47
182
  await fs.mkdir(dest, { recursive: true });
48
183
  // 1. Try capability package extract-zip if already available in environment
@@ -58,53 +193,107 @@ async function extractArchive(source, dest) {
58
193
  }
59
194
  const isZip = source.toLowerCase().endsWith('.zip') || source.toLowerCase().endsWith('.jar');
60
195
  const isTar = /\.(tar|tar\.gz|tgz|tar\.bz2|tar\.xz)$/i.test(source);
61
- // 2. Native unzip on macOS / Linux
196
+ // 2. Native unzip on macOS / Linux (pre-checked against Zip-Slip and symlinks)
62
197
  if (isZip) {
63
198
  try {
64
- execFileSync('unzip', ['-q', '-o', source, '-d', dest], { stdio: 'pipe' });
199
+ precheckNativeZipEntries(source);
200
+ execFileSync('unzip', ['-q', '-o', source, '-d', dest], {
201
+ stdio: 'pipe',
202
+ timeout: 60_000,
203
+ maxBuffer: 10 * 1024 * 1024,
204
+ windowsHide: true
205
+ });
65
206
  return { success: true, output: `Extracted successfully to ${dest} (via unzip)` };
66
207
  }
67
- catch {
208
+ catch (zipErr) {
209
+ const msg = String(zipErr?.message || '');
210
+ if (msg.startsWith('Refusing ')) {
211
+ return { success: false, error: msg };
212
+ }
68
213
  // Fall through to python3 or powershell
69
214
  }
70
215
  }
71
- // 3. Native tar on macOS / Linux
216
+ // 3. Native tar on macOS / Linux (pre-checked against Tar-Slip and symlinks)
72
217
  if (isTar || !isZip) {
73
218
  try {
74
- execFileSync('tar', ['-xf', source, '-C', dest], { stdio: 'pipe' });
219
+ precheckNativeTarEntries(source);
220
+ execFileSync('tar', ['-xf', source, '-C', dest], {
221
+ stdio: 'pipe',
222
+ timeout: 60_000,
223
+ maxBuffer: 10 * 1024 * 1024,
224
+ windowsHide: true
225
+ });
75
226
  return { success: true, output: `Extracted successfully to ${dest} (via tar)` };
76
227
  }
77
- catch {
228
+ catch (tarErr) {
229
+ const msg = String(tarErr?.message || '');
230
+ if (msg.startsWith('Refusing ')) {
231
+ return { success: false, error: msg };
232
+ }
78
233
  // Fall through
79
234
  }
80
235
  }
81
- // 4. Cross-platform Python standard library fallback
236
+ // 4. Cross-platform Python standard library fallback (Zip-Slip & Tar-Slip safe)
82
237
  try {
83
238
  execFileSync('python3', [
84
239
  '-c',
85
- 'import zipfile, tarfile, sys, os\n' +
86
- 'src, dst = sys.argv[1], sys.argv[2]\n' +
240
+ 'import zipfile, tarfile, sys, os, stat\n' +
241
+ 'src, dst = sys.argv[1], os.path.realpath(sys.argv[2])\n' +
242
+ 'max_bytes = 256 * 1024 * 1024\n' +
243
+ 'def safe_target(name):\n' +
244
+ ' if not name or name.startswith("/") or name.startswith("\\\\") or (len(name) > 1 and name[1] == ":"):\n' +
245
+ ' raise ValueError(f"Unsafe archive entry path: {name}")\n' +
246
+ ' out = os.path.realpath(os.path.join(dst, name))\n' +
247
+ ' if out != dst and not out.startswith(dst + os.sep):\n' +
248
+ ' raise ValueError(f"Archive path traversal blocked: {name}")\n' +
249
+ ' return out\n' +
87
250
  'if zipfile.is_zipfile(src):\n' +
88
251
  ' with zipfile.ZipFile(src, "r") as z:\n' +
252
+ ' total = 0\n' +
253
+ ' for info in z.infolist():\n' +
254
+ ' if stat.S_ISLNK(info.external_attr >> 16):\n' +
255
+ ' raise ValueError(f"Refusing symlink archive entry: {info.filename}")\n' +
256
+ ' total += info.file_size\n' +
257
+ ' if total > max_bytes:\n' +
258
+ ' raise ValueError("Archive exceeds 256 MB uncompressed safety limit")\n' +
259
+ ' safe_target(info.filename)\n' +
89
260
  ' z.extractall(dst)\n' +
90
261
  'elif tarfile.is_tarfile(src):\n' +
91
262
  ' with tarfile.open(src, "r:*") as t:\n' +
92
- ' t.extractall(dst)\n' +
263
+ ' total = 0\n' +
264
+ ' members = t.getmembers()\n' +
265
+ ' for m in members:\n' +
266
+ ' if m.issym() or m.islnk() or m.isdev() or m.isfifo():\n' +
267
+ ' raise ValueError(f"Refusing unsafe tar entry: {m.name}")\n' +
268
+ ' total += max(0, m.size)\n' +
269
+ ' if total > max_bytes:\n' +
270
+ ' raise ValueError("Archive exceeds 256 MB uncompressed safety limit")\n' +
271
+ ' safe_target(m.name)\n' +
272
+ ' t.extractall(dst, members=members)\n' +
93
273
  'else:\n' +
94
274
  ' raise ValueError("Unrecognized archive format")\n',
95
275
  source,
96
276
  dest
97
- ], { stdio: 'pipe' });
277
+ ], { stdio: 'pipe', timeout: 60_000, maxBuffer: 10 * 1024 * 1024, windowsHide: true });
98
278
  return { success: true, output: `Extracted successfully to ${dest} (via python3)` };
99
279
  }
100
- catch {
280
+ catch (pyErr) {
281
+ const pyMsg = String(pyErr?.stderr || pyErr?.message || '');
282
+ if (/traversal|unsafe|symlink|256 MB/i.test(pyMsg)) {
283
+ return { success: false, error: `Refused unsafe archive extraction: ${pyMsg.trim()}` };
284
+ }
101
285
  // Fall through
102
286
  }
103
287
  // 5. Windows PowerShell fallback
104
288
  if (process.platform === 'win32') {
105
289
  try {
106
- const psScript = `Expand-Archive -Path '${source.replace(/'/g, "''")}' -DestinationPath '${dest.replace(/'/g, "''")}' -Force`;
107
- execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', psScript], { stdio: 'pipe' });
290
+ const psScript = `Expand-Archive -LiteralPath '${source.replace(/'/g, "''")}' -DestinationPath '${dest.replace(/'/g, "''")}' -Force`;
291
+ execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', psScript], {
292
+ stdio: 'pipe',
293
+ timeout: 60_000,
294
+ maxBuffer: 10 * 1024 * 1024,
295
+ windowsHide: true
296
+ });
108
297
  return { success: true, output: `Extracted successfully to ${dest} (via PowerShell)` };
109
298
  }
110
299
  catch (e) {
@@ -120,21 +309,39 @@ async function compressArchive(source, dest) {
120
309
  try {
121
310
  const archiver = await loadCapabilityPackage('archiver');
122
311
  if (typeof archiver === 'function') {
123
- return await new Promise(async (resolve) => {
312
+ return await new Promise((resolve) => {
313
+ let settled = false;
314
+ const settle = (res) => {
315
+ if (settled)
316
+ return;
317
+ settled = true;
318
+ resolve(res);
319
+ };
124
320
  const output = createWriteStream(dest);
125
- const format = dest.toLowerCase().endsWith('.tar') || dest.toLowerCase().endsWith('.tar.gz') ? 'tar' : 'zip';
126
- const archiveStream = archiver(format, { zlib: { level: 9 } });
127
- output.on('close', () => resolve({ success: true, output: `Compressed ${archiveStream.pointer()} total bytes to ${dest}` }));
128
- archiveStream.on('error', (err) => resolve({ success: false, error: err.message }));
321
+ const lowerDest = dest.toLowerCase();
322
+ const isTarGz = lowerDest.endsWith('.tar.gz') || lowerDest.endsWith('.tgz');
323
+ const format = lowerDest.endsWith('.tar') || isTarGz ? 'tar' : 'zip';
324
+ const archiveStream = archiver(format, format === 'tar' ? { gzip: isTarGz } : { zlib: { level: 9 } });
325
+ output.on('close', () => settle({ success: true, output: `Compressed ${archiveStream.pointer()} total bytes to ${dest}` }));
326
+ output.on('error', (err) => settle({ success: false, error: err?.message || String(err) }));
327
+ archiveStream.on('error', (err) => settle({ success: false, error: err?.message || String(err) }));
129
328
  archiveStream.pipe(output);
130
- const stat = statSync(source);
131
- if (stat.isDirectory()) {
132
- archiveStream.directory(source, false);
329
+ try {
330
+ const stat = statSync(source);
331
+ if (stat.isDirectory()) {
332
+ archiveStream.directory(source, false);
333
+ }
334
+ else {
335
+ archiveStream.file(source, { name: path.basename(source) });
336
+ }
337
+ Promise.resolve(archiveStream.finalize()).catch((err) => {
338
+ settle({ success: false, error: err?.message || String(err) });
339
+ });
133
340
  }
134
- else {
135
- archiveStream.file(source, { name: path.basename(source) });
341
+ catch (err) {
342
+ output.destroy();
343
+ settle({ success: false, error: err?.message || String(err) });
136
344
  }
137
- await archiveStream.finalize();
138
345
  });
139
346
  }
140
347
  }
@@ -143,15 +350,17 @@ async function compressArchive(source, dest) {
143
350
  }
144
351
  const isZip = dest.toLowerCase().endsWith('.zip');
145
352
  const isTar = /\.(tar|tar\.gz|tgz)$/i.test(dest);
353
+ const isTarGz = /\.(tar\.gz|tgz)$/i.test(dest);
146
354
  const stat = statSync(source);
355
+ const execOpts = { stdio: 'pipe', timeout: 60_000, maxBuffer: 10 * 1024 * 1024, windowsHide: true };
147
356
  // 2. Native zip on macOS / Linux
148
357
  if (isZip) {
149
358
  try {
150
359
  if (stat.isDirectory()) {
151
- execFileSync('zip', ['-q', '-r', dest, '.'], { cwd: source, stdio: 'pipe' });
360
+ execFileSync('zip', ['-q', '-r', dest, '.'], { cwd: source, ...execOpts });
152
361
  }
153
362
  else {
154
- execFileSync('zip', ['-q', dest, path.basename(source)], { cwd: path.dirname(source), stdio: 'pipe' });
363
+ execFileSync('zip', ['-q', dest, '--', path.basename(source)], { cwd: path.dirname(source), ...execOpts });
155
364
  }
156
365
  return { success: true, output: `Compressed successfully to ${dest} (via zip)` };
157
366
  }
@@ -162,11 +371,12 @@ async function compressArchive(source, dest) {
162
371
  // 3. Native tar on macOS / Linux
163
372
  if (isTar) {
164
373
  try {
374
+ const tarFlag = isTarGz ? '-czf' : '-cf';
165
375
  if (stat.isDirectory()) {
166
- execFileSync('tar', ['-czf', dest, '-C', source, '.'], { stdio: 'pipe' });
376
+ execFileSync('tar', [tarFlag, dest, '-C', source, '.'], execOpts);
167
377
  }
168
378
  else {
169
- execFileSync('tar', ['-czf', dest, '-C', path.dirname(source), path.basename(source)], { stdio: 'pipe' });
379
+ execFileSync('tar', [tarFlag, dest, '-C', path.dirname(source), '--', path.basename(source)], execOpts);
170
380
  }
171
381
  return { success: true, output: `Compressed successfully to ${dest} (via tar)` };
172
382
  }
@@ -191,7 +401,7 @@ async function compressArchive(source, dest) {
191
401
  ' z.write(src, os.path.basename(src))\n',
192
402
  source,
193
403
  dest
194
- ], { stdio: 'pipe' });
404
+ ], execOpts);
195
405
  return { success: true, output: `Compressed successfully to ${dest} (via python3 zipfile)` };
196
406
  }
197
407
  catch (pyErr) {