@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Causyne Agent — Persisted Same-Session Goal Loop State Machine & Tool
3
+ *
4
+ * Implements a CAS-revisioned multi-round goal tracker (`active | paused | blocked | complete`)
5
+ * with strict safety invariants:
6
+ * - Durable state persisted atomically per session under `~/.causyne/goals/`.
7
+ * - Process-local `armed` / `disarmed` activation is NEVER persisted, so resumed
8
+ * or forked sessions never silently auto-drive without human confirmation.
9
+ * - Anti-premature-give-up gate rejects `blocked` before `minRoundsBeforeBlock`
10
+ * (default 3) consecutive rounds have been executed.
11
+ * - Subagents cannot create, pause, or resume top-level user goals.
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import crypto from 'node:crypto';
17
+ import { atomicWriteFileSync } from '../infra/atomicWriter.js';
18
+ import { causyneHome } from '../utils/paths.js';
19
+ import { boundedInteger, sanitizeToolError, type ToolWorkspaceContext } from '../tools/toolPathSafety.js';
20
+
21
+ export type GoalPhase = 'active' | 'paused' | 'blocked' | 'complete';
22
+
23
+ export interface PersistedGoalRecord {
24
+ id: string;
25
+ sessionId: string;
26
+ revision: number;
27
+ objective: string;
28
+ phase: GoalPhase;
29
+ roundsStarted: number;
30
+ consecutiveRounds: number;
31
+ maxRounds: number;
32
+ minRoundsBeforeBlock: number;
33
+ summary: string;
34
+ blocker: string;
35
+ createdAt: number;
36
+ updatedAt: number;
37
+ }
38
+
39
+ export interface GoalRuntimeView extends PersistedGoalRecord {
40
+ activation: 'armed' | 'disarmed';
41
+ }
42
+
43
+ const DEFAULT_MAX_ROUNDS = 24;
44
+ const DEFAULT_MIN_ROUNDS_BEFORE_BLOCK = 3;
45
+ const SAFE_SESSION_KEY_RE = /[^a-zA-Z0-9_-]/g;
46
+
47
+ // Process-local activation map — intentionally never persisted to disk
48
+ const armedSessions = new Map<string, { goalId: string; revision: number }>();
49
+
50
+ function goalFilePath(sessionId: string): string {
51
+ const safeId = String(sessionId || 'default').replace(SAFE_SESSION_KEY_RE, '_').slice(0, 80) || 'default';
52
+ return path.join(causyneHome(), 'goals', `${safeId}.json`);
53
+ }
54
+
55
+ function readPersistedGoal(sessionId: string): PersistedGoalRecord | null {
56
+ const filePath = goalFilePath(sessionId);
57
+ if (!fs.existsSync(filePath)) return null;
58
+ try {
59
+ const stat = fs.lstatSync(filePath);
60
+ if (stat.isSymbolicLink() || !stat.isFile()) return null;
61
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<PersistedGoalRecord>;
62
+ if (!parsed || typeof parsed.id !== 'string' || typeof parsed.objective !== 'string') return null;
63
+ return {
64
+ id: parsed.id,
65
+ sessionId: parsed.sessionId || sessionId,
66
+ revision: Number.isInteger(parsed.revision) ? Number(parsed.revision) : 1,
67
+ objective: parsed.objective,
68
+ phase: parsed.phase === 'paused' || parsed.phase === 'blocked' || parsed.phase === 'complete' ? parsed.phase : 'active',
69
+ roundsStarted: Number.isInteger(parsed.roundsStarted) ? Number(parsed.roundsStarted) : 0,
70
+ consecutiveRounds: Number.isInteger(parsed.consecutiveRounds) ? Number(parsed.consecutiveRounds) : 0,
71
+ maxRounds: Number.isInteger(parsed.maxRounds) ? Number(parsed.maxRounds) : DEFAULT_MAX_ROUNDS,
72
+ minRoundsBeforeBlock: Number.isInteger(parsed.minRoundsBeforeBlock) ? Number(parsed.minRoundsBeforeBlock) : DEFAULT_MIN_ROUNDS_BEFORE_BLOCK,
73
+ summary: typeof parsed.summary === 'string' ? parsed.summary : '',
74
+ blocker: typeof parsed.blocker === 'string' ? parsed.blocker : '',
75
+ createdAt: Number(parsed.createdAt || Date.now()),
76
+ updatedAt: Number(parsed.updatedAt || Date.now())
77
+ };
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ function writePersistedGoal(record: PersistedGoalRecord): void {
84
+ const filePath = goalFilePath(record.sessionId);
85
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
86
+ atomicWriteFileSync(filePath, `${JSON.stringify(record, null, 2)}\n`);
87
+ }
88
+
89
+ function attachActivation(record: PersistedGoalRecord): GoalRuntimeView {
90
+ const armed = armedSessions.get(record.sessionId);
91
+ const isArmed = Boolean(
92
+ record.phase === 'active'
93
+ && armed
94
+ && armed.goalId === record.id
95
+ && armed.revision === record.revision
96
+ );
97
+ return { ...record, activation: isArmed ? 'armed' : 'disarmed' };
98
+ }
99
+
100
+ export class GoalManager {
101
+ public getGoal(sessionId: string): GoalRuntimeView | null {
102
+ const rec = readPersistedGoal(sessionId);
103
+ return rec ? attachActivation(rec) : null;
104
+ }
105
+
106
+ public createGoal(options: {
107
+ sessionId: string;
108
+ objective: string;
109
+ maxRounds?: number | undefined;
110
+ minRoundsBeforeBlock?: number | undefined;
111
+ arm?: boolean | undefined;
112
+ }): GoalRuntimeView {
113
+ const objective = String(options.objective || '').trim();
114
+ if (!objective || objective.length > 4000) {
115
+ throw new Error('Goal objective must contain 1-4000 characters.');
116
+ }
117
+ const now = Date.now();
118
+ const record: PersistedGoalRecord = {
119
+ id: `goal_${crypto.randomBytes(6).toString('hex')}`,
120
+ sessionId: options.sessionId,
121
+ revision: 1,
122
+ objective,
123
+ phase: 'active',
124
+ roundsStarted: 0,
125
+ consecutiveRounds: 0,
126
+ maxRounds: boundedInteger(options.maxRounds, DEFAULT_MAX_ROUNDS, 1, 256),
127
+ minRoundsBeforeBlock: boundedInteger(options.minRoundsBeforeBlock, DEFAULT_MIN_ROUNDS_BEFORE_BLOCK, 1, 20),
128
+ summary: '',
129
+ blocker: '',
130
+ createdAt: now,
131
+ updatedAt: now
132
+ };
133
+ writePersistedGoal(record);
134
+ if (options.arm !== false) {
135
+ armedSessions.set(record.sessionId, { goalId: record.id, revision: record.revision });
136
+ } else {
137
+ armedSessions.delete(record.sessionId);
138
+ }
139
+ return attachActivation(record);
140
+ }
141
+
142
+ public updateGoal(options: {
143
+ sessionId: string;
144
+ action: 'edit' | 'pause' | 'resume' | 'advance' | 'complete' | 'blocked' | 'clear';
145
+ expectedRevision?: number | undefined;
146
+ objective?: string | undefined;
147
+ summary?: string | undefined;
148
+ blocker?: string | undefined;
149
+ isHumanInitiated?: boolean | undefined;
150
+ }): GoalRuntimeView | null {
151
+ const existing = readPersistedGoal(options.sessionId);
152
+ if (options.action === 'clear') {
153
+ armedSessions.delete(options.sessionId);
154
+ const fp = goalFilePath(options.sessionId);
155
+ if (fs.existsSync(fp)) fs.unlinkSync(fp);
156
+ return null;
157
+ }
158
+ if (!existing) {
159
+ throw new Error('No active goal exists in this session.');
160
+ }
161
+ if (options.expectedRevision !== undefined && existing.revision !== options.expectedRevision) {
162
+ throw new Error(`Goal revision conflict (expected ${options.expectedRevision}, actual ${existing.revision}).`);
163
+ }
164
+
165
+ const next: PersistedGoalRecord = {
166
+ ...existing,
167
+ revision: existing.revision + 1,
168
+ updatedAt: Date.now()
169
+ };
170
+
171
+ if (options.action === 'edit') {
172
+ const objective = String(options.objective || '').trim();
173
+ if (!objective || objective.length > 4000) throw new Error('Updated objective must contain 1-4000 characters.');
174
+ next.objective = objective;
175
+ next.consecutiveRounds = 0;
176
+ } else if (options.action === 'pause') {
177
+ next.phase = 'paused';
178
+ armedSessions.delete(options.sessionId);
179
+ } else if (options.action === 'resume') {
180
+ if (existing.phase === 'paused' && options.isHumanInitiated !== true) {
181
+ throw new Error('GOAL_TOOL_RESUME_PAUSED: Only a direct human turn can resume a paused goal.');
182
+ }
183
+ next.phase = 'active';
184
+ next.blocker = '';
185
+ armedSessions.set(options.sessionId, { goalId: next.id, revision: next.revision });
186
+ } else if (options.action === 'advance') {
187
+ if (existing.phase !== 'active') throw new Error(`Cannot advance goal in phase "${existing.phase}".`);
188
+ if (existing.roundsStarted >= existing.maxRounds) {
189
+ next.phase = 'blocked';
190
+ next.blocker = `Reached round limit (${existing.maxRounds}).`;
191
+ armedSessions.delete(options.sessionId);
192
+ } else {
193
+ next.roundsStarted += 1;
194
+ next.consecutiveRounds += 1;
195
+ armedSessions.set(options.sessionId, { goalId: next.id, revision: next.revision });
196
+ }
197
+ } else if (options.action === 'complete') {
198
+ const summary = String(options.summary || '').trim();
199
+ if (!summary) throw new Error('Completing a goal requires a grounded verification summary.');
200
+ next.phase = 'complete';
201
+ next.summary = summary.slice(0, 4000);
202
+ next.blocker = '';
203
+ armedSessions.delete(options.sessionId);
204
+ } else if (options.action === 'blocked') {
205
+ const blocker = String(options.blocker || '').trim();
206
+ if (!blocker) throw new Error('Marking a goal blocked requires a concrete blocker description.');
207
+ if (existing.consecutiveRounds < existing.minRoundsBeforeBlock && options.isHumanInitiated !== true) {
208
+ throw new Error(
209
+ `GOAL_TOOL_BLOCK_THRESHOLD: Cannot mark goal blocked after only ${existing.consecutiveRounds} round(s); `
210
+ + `at least ${existing.minRoundsBeforeBlock} consecutive rounds are required before giving up.`
211
+ );
212
+ }
213
+ next.phase = 'blocked';
214
+ next.blocker = blocker.slice(0, 2000);
215
+ armedSessions.delete(options.sessionId);
216
+ }
217
+
218
+ writePersistedGoal(next);
219
+ return attachActivation(next);
220
+ }
221
+ }
222
+
223
+ export const goalManager = new GoalManager();
224
+
225
+ export const goalLoopTool = {
226
+ schema: {
227
+ name: 'goal',
228
+ description:
229
+ 'Manage a persistent, CAS-revisioned multi-round goal for the current session (status, create, edit, pause, resume, advance, complete, blocked, clear). Enforces anti-premature-block thresholds and non-persisted armed/disarmed activation safety.',
230
+ parameters: {
231
+ type: 'object',
232
+ properties: {
233
+ action: {
234
+ type: 'string',
235
+ enum: ['status', 'create', 'edit', 'pause', 'resume', 'advance', 'complete', 'blocked', 'clear']
236
+ },
237
+ objective: { type: 'string', description: 'Goal objective (required for create/edit).' },
238
+ summary: { type: 'string', description: 'Grounded completion summary with verified evidence (required for complete).' },
239
+ blocker: { type: 'string', description: 'Concrete blocker explanation (required for blocked).' },
240
+ expectedRevision: { type: 'integer', description: 'Optional CAS revision guard.' },
241
+ maxRounds: { type: 'integer', description: 'Maximum autonomous rounds (1-256, default 24).' }
242
+ },
243
+ required: ['action'],
244
+ additionalProperties: false
245
+ }
246
+ },
247
+
248
+ async execute(
249
+ args: {
250
+ action: 'status' | 'create' | 'edit' | 'pause' | 'resume' | 'advance' | 'complete' | 'blocked' | 'clear';
251
+ objective?: string;
252
+ summary?: string;
253
+ blocker?: string;
254
+ expectedRevision?: number;
255
+ maxRounds?: number;
256
+ },
257
+ context: ToolWorkspaceContext & {
258
+ isSubagent?: boolean | undefined;
259
+ parentLoop?: { sessionId?: string | undefined; taskId?: string | undefined } | undefined;
260
+ } = {}
261
+ ) {
262
+ try {
263
+ if (context.isSubagent) {
264
+ return { success: false, error: 'Subagents cannot mutate top-level session goals.' };
265
+ }
266
+ const sessionId = context.parentLoop?.sessionId || context.parentLoop?.taskId || 'default';
267
+ if (args.action === 'status') {
268
+ const current = goalManager.getGoal(sessionId);
269
+ return {
270
+ success: true,
271
+ goal: current,
272
+ output: current
273
+ ? `Goal ${current.id} (rev ${current.revision}, phase=${current.phase}, ${current.activation}, rounds=${current.roundsStarted}/${current.maxRounds}): ${current.objective}`
274
+ : 'No persisted goal for this session.'
275
+ };
276
+ }
277
+ if (args.action === 'create') {
278
+ const created = goalManager.createGoal({
279
+ sessionId,
280
+ objective: args.objective || '',
281
+ maxRounds: args.maxRounds
282
+ });
283
+ return {
284
+ success: true,
285
+ goal: created,
286
+ output: `Created goal ${created.id} (rev ${created.revision}, armed): ${created.objective}`
287
+ };
288
+ }
289
+ const updated = goalManager.updateGoal({
290
+ sessionId,
291
+ action: args.action,
292
+ expectedRevision: args.expectedRevision,
293
+ objective: args.objective,
294
+ summary: args.summary,
295
+ blocker: args.blocker,
296
+ isHumanInitiated: false
297
+ });
298
+ if (!updated) {
299
+ return { success: true, goal: null, output: 'Cleared session goal.' };
300
+ }
301
+ return {
302
+ success: true,
303
+ goal: updated,
304
+ output: `Updated goal ${updated.id} -> phase=${updated.phase} (rev ${updated.revision}, rounds=${updated.roundsStarted}/${updated.maxRounds})`
305
+ };
306
+ } catch (error) {
307
+ return { success: false, error: sanitizeToolError(error) };
308
+ }
309
+ }
310
+ };
package/src/entrypoint.js CHANGED
@@ -93,7 +93,7 @@ program
93
93
  .option('--resume', 'Reuse active workspace session instead of an isolated ephemeral session')
94
94
  .option('--session <id>', 'Resume a specific session ID for headless runs')
95
95
  .option('--json-schema <schema>', 'Require and validate JSON response matching inline JSON or file path')
96
- .option('--permission-mode <mode>', 'Autonomy mode override for this run (A, B, or C)')
96
+ .option('--permission-mode <preset>', 'Permission preset override for this run (read-only, workspace-write, or full-access)')
97
97
  .option('-v', 'output the version number')
98
98
  .version(pkgVersion, '-V, --version')
99
99
  .action(async (options) => {
@@ -235,6 +235,138 @@ program
235
235
  process.once('SIGINT', () => { void shutdown(); });
236
236
  process.once('SIGTERM', () => { void shutdown(); });
237
237
  });
238
+ program
239
+ .command('game [action]')
240
+ .description('Launch, inspect, or install Causyne Game (official separate AI Game Studio in your browser)')
241
+ .option('-p, --port <number>', 'Loopback port (0 = auto)', '0')
242
+ .option('-d, --dir <directory>', 'Explicit path to a local causyne-game checkout')
243
+ .option('--no-open', 'Do not automatically open Causyne Game in your browser')
244
+ .option('-y, --yes', 'Confirm manifest-verified download when running "causyne game install"')
245
+ .option('--manifest <url>', 'Override Causyne Game release manifest URL or local file path')
246
+ .option('--json', 'Emit status or startup details as a single JSON line')
247
+ .action(async (action, options) => {
248
+ const mode = String(action || 'start').trim().toLowerCase();
249
+ const { getGameStudioStatus, launchGameStudio, stopGameStudio } = await import('./game/gameLauncher.js');
250
+ const { defaultGameManifestUrl, installGameStudio, locateGameStudio } = await import('./game/gameProvisioner.js');
251
+ if (mode === 'status') {
252
+ const located = locateGameStudio(options.dir ? resolveUserPath(String(options.dir)) : undefined);
253
+ const running = getGameStudioStatus();
254
+ const payload = {
255
+ installed: Boolean(located),
256
+ ...(located ? { dir: located.dir, source: located.source, version: located.version, hasStudioBuild: located.hasStudioBuild, hasNodeModules: located.hasNodeModules } : {}),
257
+ manifestUrl: defaultGameManifestUrl(),
258
+ running
259
+ };
260
+ if (options.json) {
261
+ process.stdout.write(`${JSON.stringify(payload)}\n`);
262
+ return;
263
+ }
264
+ console.log('');
265
+ console.log('Causyne Game Status');
266
+ if (located) {
267
+ console.log(` Installed : yes (${located.source}${located.version ? ` · v${located.version}` : ''})`);
268
+ console.log(` Location : ${safeDisplay(located.dir)}`);
269
+ console.log(` Ready : ${located.hasNodeModules && located.hasStudioBuild ? 'ready' : 'needs build/deps'}`);
270
+ }
271
+ else {
272
+ console.log(' Installed : no (run "causyne game install --yes" or set CAUSYNE_GAME_DIR)');
273
+ }
274
+ console.log(` Manifest : ${defaultGameManifestUrl()}`);
275
+ console.log(` Server : ${running.running ? `running at ${running.url}` : 'not running in this process'}`);
276
+ console.log('');
277
+ return;
278
+ }
279
+ if (mode === 'install') {
280
+ const result = await installGameStudio({
281
+ confirm: Boolean(options.yes),
282
+ manifestUrl: options.manifest ? String(options.manifest) : undefined
283
+ });
284
+ if (options.json) {
285
+ process.stdout.write(`${JSON.stringify(result)}\n`);
286
+ if (!result.success && !result.requiresConsent)
287
+ process.exitCode = 1;
288
+ return;
289
+ }
290
+ if (result.requiresConsent) {
291
+ console.log('');
292
+ console.log(`Causyne Game v${result.version ?? 'latest'} is available from ${result.manifestUrl}.`);
293
+ if (result.license)
294
+ console.log(` License : ${result.license}`);
295
+ if (result.size)
296
+ console.log(` Size : ${(result.size / (1024 * 1024)).toFixed(1)} MB (SHA-256 verified)`);
297
+ console.log('Re-run with --yes to download and install into ~/.causyne/game/.');
298
+ console.log('');
299
+ return;
300
+ }
301
+ if (!result.success) {
302
+ console.error(`Causyne Game install failed: ${result.error || 'unknown error'}`);
303
+ process.exitCode = 1;
304
+ return;
305
+ }
306
+ console.log(result.alreadyInstalled
307
+ ? `Causyne Game v${result.version ?? ''} is already installed at ${safeDisplay(result.path || '')}.`
308
+ : `Installed Causyne Game v${result.version ?? ''} to ${safeDisplay(result.path || '')}.`);
309
+ return;
310
+ }
311
+ if (mode !== 'start' && mode !== 'open') {
312
+ console.error(`Unknown game action "${safeDisplay(mode)}". Expected: start, status, or install.`);
313
+ process.exitCode = 1;
314
+ return;
315
+ }
316
+ const parsedPort = Number.parseInt(String(options.port ?? '0'), 10);
317
+ const port = Number.isInteger(parsedPort) && parsedPort >= 0 && parsedPort <= 65535 ? parsedPort : 0;
318
+ const explicitDir = options.dir ? resolveUserPath(String(options.dir)) : undefined;
319
+ const shouldOpen = options.open !== false && !options.json && process.stdout.isTTY;
320
+ let launched;
321
+ try {
322
+ launched = await launchGameStudio({
323
+ dir: explicitDir,
324
+ port,
325
+ openBrowser: shouldOpen
326
+ });
327
+ }
328
+ catch (error) {
329
+ const msg = error instanceof Error ? error.message : String(error);
330
+ if (options.json) {
331
+ process.stdout.write(`${JSON.stringify({ ok: false, error: msg })}\n`);
332
+ }
333
+ else {
334
+ console.error(`Causyne Game failed to start: ${msg}`);
335
+ }
336
+ process.exitCode = 1;
337
+ return;
338
+ }
339
+ if (options.json) {
340
+ process.stdout.write(`${JSON.stringify({
341
+ ok: true,
342
+ url: launched.url,
343
+ origin: launched.origin,
344
+ port: launched.port,
345
+ dir: launched.dir,
346
+ source: launched.source,
347
+ version: launched.version
348
+ })}\n`);
349
+ }
350
+ else {
351
+ console.log('');
352
+ console.log('Causyne Game Studio running (127.0.0.1 loopback only)');
353
+ console.log(` Open URL : ${launched.url}`);
354
+ console.log(` Source : ${launched.source}${launched.version ? ` (v${launched.version})` : ''} · ${safeDisplay(launched.dir)}`);
355
+ console.log(' Primary : Causyne Agent (ACP + workspace MCP)');
356
+ if (launched.openedBrowser)
357
+ console.log(' Browser : Opened in your default browser');
358
+ else if (launched.browserHint)
359
+ console.log(` Remote : ${safeDisplay(launched.browserHint)}`);
360
+ console.log(' Stop : Press Ctrl+C (exits cleanly, no background daemon)');
361
+ console.log('');
362
+ }
363
+ const shutdown = async () => {
364
+ await stopGameStudio();
365
+ process.exit(0);
366
+ };
367
+ process.once('SIGINT', () => { void shutdown(); });
368
+ process.once('SIGTERM', () => { void shutdown(); });
369
+ });
238
370
  program
239
371
  .command('status')
240
372
  .description('Show local provider, workspace and runtime status')
@@ -264,7 +396,7 @@ program
264
396
  .option('--resume', 'Reuse active workspace session instead of an isolated ephemeral session')
265
397
  .option('--session <id>', 'Resume a specific session ID for this run')
266
398
  .option('--json-schema <schema>', 'Require and validate JSON response matching inline JSON or file path')
267
- .option('--permission-mode <mode>', 'Autonomy mode override for this run (A, B, or C)')
399
+ .option('--permission-mode <preset>', 'Permission preset override for this run (read-only, workspace-write, or full-access)')
268
400
  .action(async (task, options) => {
269
401
  announceDevEmulator(options.devEmulator);
270
402
  try {
@@ -314,7 +446,7 @@ program
314
446
  .option('-m, --model <name>', 'Override model for this chat session without modifying saved config')
315
447
  .option('--provider <name>', 'Override provider for this chat session without modifying saved config')
316
448
  .option('--variant <level>', 'Override reasoning variant/effort for this chat session without modifying saved config')
317
- .option('--permission-mode <mode>', 'Autonomy mode override for this chat session (A, B, or C)')
449
+ .option('--permission-mode <preset>', 'Permission preset override for this chat session (read-only, workspace-write, or full-access)')
318
450
  .action(async (options) => {
319
451
  announceDevEmulator(options.devEmulator);
320
452
  try {
package/src/entrypoint.ts CHANGED
@@ -100,7 +100,7 @@ program
100
100
  .option('--resume', 'Reuse active workspace session instead of an isolated ephemeral session')
101
101
  .option('--session <id>', 'Resume a specific session ID for headless runs')
102
102
  .option('--json-schema <schema>', 'Require and validate JSON response matching inline JSON or file path')
103
- .option('--permission-mode <mode>', 'Autonomy mode override for this run (A, B, or C)')
103
+ .option('--permission-mode <preset>', 'Permission preset override for this run (read-only, workspace-write, or full-access)')
104
104
  .option('-v', 'output the version number')
105
105
  .version(pkgVersion, '-V, --version')
106
106
  .action(async (options: Record<string, any>) => {
@@ -243,6 +243,139 @@ program
243
243
  process.once('SIGTERM', () => { void shutdown(); });
244
244
  });
245
245
 
246
+ program
247
+ .command('game [action]')
248
+ .description('Launch, inspect, or install Causyne Game (official separate AI Game Studio in your browser)')
249
+ .option('-p, --port <number>', 'Loopback port (0 = auto)', '0')
250
+ .option('-d, --dir <directory>', 'Explicit path to a local causyne-game checkout')
251
+ .option('--no-open', 'Do not automatically open Causyne Game in your browser')
252
+ .option('-y, --yes', 'Confirm manifest-verified download when running "causyne game install"')
253
+ .option('--manifest <url>', 'Override Causyne Game release manifest URL or local file path')
254
+ .option('--json', 'Emit status or startup details as a single JSON line')
255
+ .action(async (action: string | undefined, options: Record<string, any>) => {
256
+ const mode = String(action || 'start').trim().toLowerCase();
257
+ const { getGameStudioStatus, launchGameStudio, stopGameStudio } = await import('./game/gameLauncher.js');
258
+ const { defaultGameManifestUrl, installGameStudio, locateGameStudio } = await import('./game/gameProvisioner.js');
259
+
260
+ if (mode === 'status') {
261
+ const located = locateGameStudio(options.dir ? resolveUserPath(String(options.dir)) : undefined);
262
+ const running = getGameStudioStatus();
263
+ const payload = {
264
+ installed: Boolean(located),
265
+ ...(located ? { dir: located.dir, source: located.source, version: located.version, hasStudioBuild: located.hasStudioBuild, hasNodeModules: located.hasNodeModules } : {}),
266
+ manifestUrl: defaultGameManifestUrl(),
267
+ running
268
+ };
269
+ if (options.json) {
270
+ process.stdout.write(`${JSON.stringify(payload)}\n`);
271
+ return;
272
+ }
273
+ console.log('');
274
+ console.log('Causyne Game Status');
275
+ if (located) {
276
+ console.log(` Installed : yes (${located.source}${located.version ? ` · v${located.version}` : ''})`);
277
+ console.log(` Location : ${safeDisplay(located.dir)}`);
278
+ console.log(` Ready : ${located.hasNodeModules && located.hasStudioBuild ? 'ready' : 'needs build/deps'}`);
279
+ } else {
280
+ console.log(' Installed : no (run "causyne game install --yes" or set CAUSYNE_GAME_DIR)');
281
+ }
282
+ console.log(` Manifest : ${defaultGameManifestUrl()}`);
283
+ console.log(` Server : ${running.running ? `running at ${running.url}` : 'not running in this process'}`);
284
+ console.log('');
285
+ return;
286
+ }
287
+
288
+ if (mode === 'install') {
289
+ const result = await installGameStudio({
290
+ confirm: Boolean(options.yes),
291
+ manifestUrl: options.manifest ? String(options.manifest) : undefined
292
+ });
293
+ if (options.json) {
294
+ process.stdout.write(`${JSON.stringify(result)}\n`);
295
+ if (!result.success && !result.requiresConsent) process.exitCode = 1;
296
+ return;
297
+ }
298
+ if (result.requiresConsent) {
299
+ console.log('');
300
+ console.log(`Causyne Game v${result.version ?? 'latest'} is available from ${result.manifestUrl}.`);
301
+ if (result.license) console.log(` License : ${result.license}`);
302
+ if (result.size) console.log(` Size : ${(result.size / (1024 * 1024)).toFixed(1)} MB (SHA-256 verified)`);
303
+ console.log('Re-run with --yes to download and install into ~/.causyne/game/.');
304
+ console.log('');
305
+ return;
306
+ }
307
+ if (!result.success) {
308
+ console.error(`Causyne Game install failed: ${result.error || 'unknown error'}`);
309
+ process.exitCode = 1;
310
+ return;
311
+ }
312
+ console.log(
313
+ result.alreadyInstalled
314
+ ? `Causyne Game v${result.version ?? ''} is already installed at ${safeDisplay(result.path || '')}.`
315
+ : `Installed Causyne Game v${result.version ?? ''} to ${safeDisplay(result.path || '')}.`
316
+ );
317
+ return;
318
+ }
319
+
320
+ if (mode !== 'start' && mode !== 'open') {
321
+ console.error(`Unknown game action "${safeDisplay(mode)}". Expected: start, status, or install.`);
322
+ process.exitCode = 1;
323
+ return;
324
+ }
325
+
326
+ const parsedPort = Number.parseInt(String(options.port ?? '0'), 10);
327
+ const port = Number.isInteger(parsedPort) && parsedPort >= 0 && parsedPort <= 65535 ? parsedPort : 0;
328
+ const explicitDir = options.dir ? resolveUserPath(String(options.dir)) : undefined;
329
+ const shouldOpen = options.open !== false && !options.json && process.stdout.isTTY;
330
+
331
+ let launched;
332
+ try {
333
+ launched = await launchGameStudio({
334
+ dir: explicitDir,
335
+ port,
336
+ openBrowser: shouldOpen
337
+ });
338
+ } catch (error) {
339
+ const msg = error instanceof Error ? error.message : String(error);
340
+ if (options.json) {
341
+ process.stdout.write(`${JSON.stringify({ ok: false, error: msg })}\n`);
342
+ } else {
343
+ console.error(`Causyne Game failed to start: ${msg}`);
344
+ }
345
+ process.exitCode = 1;
346
+ return;
347
+ }
348
+
349
+ if (options.json) {
350
+ process.stdout.write(`${JSON.stringify({
351
+ ok: true,
352
+ url: launched.url,
353
+ origin: launched.origin,
354
+ port: launched.port,
355
+ dir: launched.dir,
356
+ source: launched.source,
357
+ version: launched.version
358
+ })}\n`);
359
+ } else {
360
+ console.log('');
361
+ console.log('Causyne Game Studio running (127.0.0.1 loopback only)');
362
+ console.log(` Open URL : ${launched.url}`);
363
+ console.log(` Source : ${launched.source}${launched.version ? ` (v${launched.version})` : ''} · ${safeDisplay(launched.dir)}`);
364
+ console.log(' Primary : Causyne Agent (ACP + workspace MCP)');
365
+ if (launched.openedBrowser) console.log(' Browser : Opened in your default browser');
366
+ else if (launched.browserHint) console.log(` Remote : ${safeDisplay(launched.browserHint)}`);
367
+ console.log(' Stop : Press Ctrl+C (exits cleanly, no background daemon)');
368
+ console.log('');
369
+ }
370
+
371
+ const shutdown = async () => {
372
+ await stopGameStudio();
373
+ process.exit(0);
374
+ };
375
+ process.once('SIGINT', () => { void shutdown(); });
376
+ process.once('SIGTERM', () => { void shutdown(); });
377
+ });
378
+
246
379
  program
247
380
  .command('status')
248
381
  .description('Show local provider, workspace and runtime status')
@@ -274,7 +407,7 @@ program
274
407
  .option('--resume', 'Reuse active workspace session instead of an isolated ephemeral session')
275
408
  .option('--session <id>', 'Resume a specific session ID for this run')
276
409
  .option('--json-schema <schema>', 'Require and validate JSON response matching inline JSON or file path')
277
- .option('--permission-mode <mode>', 'Autonomy mode override for this run (A, B, or C)')
410
+ .option('--permission-mode <preset>', 'Permission preset override for this run (read-only, workspace-write, or full-access)')
278
411
  .action(async (task: string | undefined, options: Record<string, any>) => {
279
412
  announceDevEmulator(options.devEmulator);
280
413
  try {
@@ -322,7 +455,7 @@ program
322
455
  .option('-m, --model <name>', 'Override model for this chat session without modifying saved config')
323
456
  .option('--provider <name>', 'Override provider for this chat session without modifying saved config')
324
457
  .option('--variant <level>', 'Override reasoning variant/effort for this chat session without modifying saved config')
325
- .option('--permission-mode <mode>', 'Autonomy mode override for this chat session (A, B, or C)')
458
+ .option('--permission-mode <preset>', 'Permission preset override for this chat session (read-only, workspace-write, or full-access)')
326
459
  .action(async (options: Record<string, any>) => {
327
460
  announceDevEmulator(options.devEmulator);
328
461
  try {