opencode-work-context 0.4.7 → 0.4.9
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.
- package/README.md +24 -4
- package/bin/opencode-work-context.js +31 -2
- package/commands/wc.md +9 -6
- package/package.json +1 -1
- package/plugin/attention-activation.js +31 -7
- package/plugin/attention.js +66 -7
- package/src/core.js +31 -8
- package/src/tool-definitions.js +1 -1
package/README.md
CHANGED
|
@@ -84,13 +84,30 @@ When you return later, continue from the active stage. A stage must have a
|
|
|
84
84
|
non-empty prompt before implementation begins; if the prompt is missing or
|
|
85
85
|
ambiguous, `/wc resume` instructs the agent to ask focused questions first.
|
|
86
86
|
Before working, the agent reports the stage essence, the previous session's
|
|
87
|
-
result or stopping point, and what it will do now.
|
|
88
|
-
|
|
87
|
+
result or stopping point, and what it will do now. The summary uses a
|
|
88
|
+
plain-language goal and, for a larger stage with explicit scope, a short
|
|
89
|
+
`In this stage we will` list of expected outcomes. Raw IDs and operation metadata
|
|
90
|
+
are omitted. The agent then continues immediately instead of asking for generic
|
|
91
|
+
confirmation. A stage can explicitly require confirmation with this standalone
|
|
92
|
+
prompt line:
|
|
93
|
+
|
|
94
|
+
```text
|
|
95
|
+
RESUME_CONFIRMATION: required
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Resume a stage with:
|
|
89
99
|
|
|
90
100
|
```text
|
|
91
101
|
/wc resume 000001 02
|
|
92
102
|
```
|
|
93
103
|
|
|
104
|
+
After updating the npm package, refresh the generated slash-command contract
|
|
105
|
+
without touching project configuration or loaders:
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
npx opencode-work-context sync-command --force
|
|
109
|
+
```
|
|
110
|
+
|
|
94
111
|
Useful commands:
|
|
95
112
|
|
|
96
113
|
```text
|
|
@@ -266,8 +283,11 @@ On Linux notification servers that support actions, `Open session` routes the
|
|
|
266
283
|
originating OpenCode process to the affected native session. If that process
|
|
267
284
|
runs in tmux, its validated `TMUX_PANE` is selected with fixed `tmux` arguments.
|
|
268
285
|
On X11, the loader records the active window with `xprop` and raises it with
|
|
269
|
-
`wmctrl` when those optional tools are available.
|
|
270
|
-
|
|
286
|
+
`wmctrl` when those optional tools are available. Pane/window activation happens
|
|
287
|
+
before session navigation so a hidden TUI can process the route change. Attention
|
|
288
|
+
is acknowledged only after the destination route is verified; failed navigation
|
|
289
|
+
leaves it unread and shows an in-TUI warning. Each activation step is independent
|
|
290
|
+
and best-effort: navigation can still succeed if pane or window activation fails.
|
|
271
291
|
Wayland focus restrictions and terminal tabs without a public activation API
|
|
272
292
|
may require the user to foreground the terminal manually. Session and window
|
|
273
293
|
identifiers never appear in notification text or configurable commands.
|
|
@@ -74,12 +74,33 @@ const hasSymlinkParent = (file) => {
|
|
|
74
74
|
};
|
|
75
75
|
|
|
76
76
|
function parseArgs(args) {
|
|
77
|
-
if (args[0]
|
|
77
|
+
if (args[0] === "sync-command") {
|
|
78
|
+
const unknown = args.slice(1).filter((arg) => arg !== "--force");
|
|
79
|
+
if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
|
|
80
|
+
return { syncCommand: true, force: args.includes("--force") };
|
|
81
|
+
}
|
|
82
|
+
if (args[0] !== "init") return fail("usage: opencode-work-context init [--force] | sync-command");
|
|
78
83
|
const unknown = args.slice(1).filter((arg) => arg !== "--force");
|
|
79
84
|
if (unknown.length) return fail(`unknown option: ${unknown[0]}`);
|
|
80
85
|
return { force: args.includes("--force") };
|
|
81
86
|
}
|
|
82
87
|
|
|
88
|
+
function syncCommandProjection(force) {
|
|
89
|
+
const relative = ".opencode/commands/wc.md";
|
|
90
|
+
const file = path.join(projectRoot, relative);
|
|
91
|
+
if (hasSymlinkParent(file) || (exists(file) && (!fs.lstatSync(file).isFile() || fs.lstatSync(file).isSymbolicLink()))) {
|
|
92
|
+
fail(`refusing to overwrite non-regular file: ${relative}`);
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
if (exists(file) && fs.readFileSync(file, "utf8") !== command && !force) {
|
|
96
|
+
fail(`refusing to overwrite existing file: ${relative}; rerun with --force`);
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
writeAtomic(file, command);
|
|
100
|
+
console.log(`Updated ${relative} from opencode-work-context ${packageManifest.version}.`);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
|
|
83
104
|
function ensurePackageJson() {
|
|
84
105
|
const file = path.join(dependencyRoot, "package.json");
|
|
85
106
|
if (fs.existsSync(file)) return;
|
|
@@ -272,7 +293,15 @@ function writeGenerated() {
|
|
|
272
293
|
}
|
|
273
294
|
|
|
274
295
|
const options = parseArgs(process.argv.slice(2));
|
|
275
|
-
if (options) {
|
|
296
|
+
if (options?.syncCommand) {
|
|
297
|
+
const initLock = acquireInitLock();
|
|
298
|
+
if (initLock.failed) process.exitCode = 1;
|
|
299
|
+
else {
|
|
300
|
+
try { syncCommandProjection(options.force); }
|
|
301
|
+
catch (error) { fail(`command sync failed: ${error.message}`); }
|
|
302
|
+
finally { releaseInitLock(initLock); }
|
|
303
|
+
}
|
|
304
|
+
} else if (options) {
|
|
276
305
|
const initLock = acquireInitLock();
|
|
277
306
|
if (initLock.failed) process.exitCode = 1;
|
|
278
307
|
else if (checkConflicts(options.force) && checkPackageConflict(options.force)) {
|
package/commands/wc.md
CHANGED
|
@@ -5,8 +5,9 @@ subtask: false
|
|
|
5
5
|
|
|
6
6
|
Interpret `/wc $ARGUMENTS` as an explicit work-context operation. Use the matching
|
|
7
7
|
`work_context_*` custom tool registered by the installed package plugin with structured arguments. Never edit work-context
|
|
8
|
-
Markdown, JSONL, INDEX, or SESSIONS projections directly. For mutating operations
|
|
9
|
-
report the structured result and stable error code.
|
|
8
|
+
Markdown, JSONL, INDEX, or SESSIONS projections directly. For mutating operations
|
|
9
|
+
other than `resume`, report the structured result and stable error code. For
|
|
10
|
+
`resume`, follow its human-oriented presentation rules instead. Use `work_context_help` when
|
|
10
11
|
the syntax is missing or ambiguous.
|
|
11
12
|
|
|
12
13
|
For `workspace list <workspace>` (or `<workspace> list`), report the workspace
|
|
@@ -65,14 +66,16 @@ Supported syntax:
|
|
|
65
66
|
- explicit workspace and stage positions accept canonical padded IDs or unpadded positive integers (`1..999999` and `1..99`); results and generated commands remain padded
|
|
66
67
|
- zero, signs, decimals, whitespace, overlong values, and other non-digit identifier forms are invalid; a lone unpadded workspace ID is not reinterpreted under the one-identifier rule
|
|
67
68
|
- `stage update-result` replaces an existing result and does not create a result for an unfinished stage
|
|
68
|
-
- `resume` returns `resume.
|
|
69
|
+
- `resume` returns `resume.presentation` and `resume.context`; before doing any work, report a concise human-oriented summary in the user's language with the stage title, a plain-language Goal, previous progress when useful, and the immediate next action
|
|
70
|
+
- when the saved prompt contains several clear deliverables, add `In this stage we will` with 2-5 short outcome-oriented bullets derived only from the prompt, previous result, and workspace knowledge; do not invent scope, and omit this block for a small stage
|
|
71
|
+
- do not expose raw workspace/stage/session identifiers, ordinals, `ok` flags, or absent error codes in the user-facing resume summary
|
|
69
72
|
- `resume.context.workspace_knowledge` contains every active durable knowledge entry for the workspace; treat it as established shared context, and do not repeat earlier analysis unless an entry is incomplete, contradicted, or needs verification
|
|
70
|
-
-
|
|
71
|
-
- when `resume.next_action` is `await_confirmation`,
|
|
73
|
+
- after presenting the summary, continue work immediately when `resume.next_action` is `start_work`; do not ask for generic confirmation
|
|
74
|
+
- a stage may require confirmation only with an exact standalone `RESUME_CONFIRMATION: required` line in its saved prompt; when `resume.next_action` is `await_confirmation`, present the summary and wait before inspecting or modifying application code
|
|
72
75
|
- `create` enters the new workspace's Planning stage in the current OpenCode session only when that session is not yet in a workspace; otherwise it only creates the workspace and its planning session
|
|
73
76
|
- `stage add` creates a stage; when the current OpenCode session is not associated with a workspace, it also enters the new stage in that session
|
|
74
77
|
- when `stage add` is invoked from an associated session, it only creates a planned stage and leaves the current stage unchanged; enter it later with an explicit `resume <workspace> <stage>` in a separate OpenCode session
|
|
75
|
-
- `resume` returns `resume.next_action` and `resume.instruction`; begin or continue implementation
|
|
78
|
+
- `resume` returns `resume.next_action` and `resume.instruction`; begin or continue implementation when the stage prompt is non-empty unless it explicitly requires confirmation or contains an unresolved decision that genuinely blocks progress
|
|
76
79
|
- when `resume.next_action` is `ask_questions`, do not inspect or modify application code and ask the user focused questions needed to make the prompt actionable
|
|
77
80
|
- before `stage finish`, review durable findings: add new knowledge, update changed knowledge, supersede obsolete knowledge, or explicitly use `knowledgeReview=none` when the stage produced no durable findings; use `knowledgeReview=added` after ledger changes
|
|
78
81
|
- invoke `stage finish` only when the user explicitly requests that lifecycle command; do not infer the request from completed work, tests, or a final report
|
package/package.json
CHANGED
|
@@ -2,6 +2,10 @@ import { spawn as nodeSpawn } from "node:child_process";
|
|
|
2
2
|
|
|
3
3
|
const WINDOW_ID = /^0x[0-9a-f]+$/i;
|
|
4
4
|
const MAX_OUTPUT = 128;
|
|
5
|
+
const routeSessionId = (api) => api?.route?.current?.name === "session"
|
|
6
|
+
? api.route.current.params?.sessionID || api.route.current.params?.sessionId || api.route.current.params?.session_id || null
|
|
7
|
+
: null;
|
|
8
|
+
const wait = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
5
9
|
|
|
6
10
|
const run = ({ executable, args, spawn, timeoutMs, capture = false, children }) => new Promise((resolve) => {
|
|
7
11
|
let child;
|
|
@@ -69,6 +73,8 @@ export const createAttentionActivator = ({
|
|
|
69
73
|
timeoutMs = 1000,
|
|
70
74
|
captureThrottleMs = 1000,
|
|
71
75
|
navigationTimeoutMs = 2000,
|
|
76
|
+
routeVerificationMs = 500,
|
|
77
|
+
activationDelayMs = 50,
|
|
72
78
|
now = () => Date.now(),
|
|
73
79
|
} = {}) => {
|
|
74
80
|
const paneId = env.TMUX && /^%\d+$/.test(env.TMUX_PANE || "") ? env.TMUX_PANE : null;
|
|
@@ -122,22 +128,40 @@ export const createAttentionActivator = ({
|
|
|
122
128
|
}
|
|
123
129
|
};
|
|
124
130
|
|
|
131
|
+
const verifyRoute = async (sessionId) => {
|
|
132
|
+
if (!("current" in (api?.route || {})) || disposed) return false;
|
|
133
|
+
const deadline = Date.now() + routeVerificationMs;
|
|
134
|
+
do {
|
|
135
|
+
if (!disposed && routeSessionId(api) === sessionId) return true;
|
|
136
|
+
if (routeVerificationMs <= 0) break;
|
|
137
|
+
await wait(Math.min(25, Math.max(1, deadline - Date.now())));
|
|
138
|
+
} while (!disposed && Date.now() < deadline);
|
|
139
|
+
return !disposed && routeSessionId(api) === sessionId;
|
|
140
|
+
};
|
|
141
|
+
|
|
125
142
|
const activate = async (sessionId) => {
|
|
126
|
-
if (disposed || typeof sessionId !== "string" || !sessionId || sessionId.length > 256)
|
|
127
|
-
|
|
128
|
-
|
|
143
|
+
if (disposed || typeof sessionId !== "string" || !sessionId || sessionId.length > 256) {
|
|
144
|
+
return { ok: false, activated: false, navigated: false, verified: false };
|
|
145
|
+
}
|
|
146
|
+
let activated = false;
|
|
129
147
|
if (paneId) {
|
|
130
148
|
const selectedWindow = await run({ executable: "tmux", args: ["select-window", "-t", paneId], spawn, timeoutMs, children });
|
|
131
|
-
if (disposed) return activated;
|
|
149
|
+
if (disposed) return { ok: false, activated, navigated: false, verified: false };
|
|
132
150
|
const selectedPane = await run({ executable: "tmux", args: ["select-pane", "-t", paneId], spawn, timeoutMs, children });
|
|
133
|
-
activated = selectedWindow.ok && selectedPane.ok
|
|
151
|
+
activated = selectedWindow.ok && selectedPane.ok;
|
|
134
152
|
}
|
|
135
|
-
if (disposed) return activated;
|
|
153
|
+
if (disposed) return { ok: false, activated, navigated: false, verified: false };
|
|
136
154
|
if (windowId && canCaptureWindow) {
|
|
137
155
|
const raised = await run({ executable: "wmctrl", args: ["-ia", windowId], spawn, timeoutMs, children });
|
|
138
156
|
activated = raised.ok || activated;
|
|
139
157
|
}
|
|
140
|
-
return activated;
|
|
158
|
+
if (disposed) return { ok: false, activated, navigated: false, verified: false };
|
|
159
|
+
if (activated && activationDelayMs > 0) await wait(activationDelayMs);
|
|
160
|
+
if (disposed) return { ok: false, activated, navigated: false, verified: false };
|
|
161
|
+
const navigated = await navigate(sessionId);
|
|
162
|
+
if (disposed) return { ok: false, activated, navigated, verified: false };
|
|
163
|
+
const verified = navigated && await verifyRoute(sessionId);
|
|
164
|
+
return { ok: verified, activated, navigated, verified };
|
|
141
165
|
};
|
|
142
166
|
|
|
143
167
|
return {
|
package/plugin/attention.js
CHANGED
|
@@ -86,6 +86,49 @@ export const acknowledgeNavigation = (api, sessionId, observedEventKey) => {
|
|
|
86
86
|
if (!sessionId || !observedEventKey) return false;
|
|
87
87
|
return api?.workContextAttention?.acknowledge?.(sessionId, observedEventKey) === true;
|
|
88
88
|
};
|
|
89
|
+
export const createPendingNavigationTracker = () => {
|
|
90
|
+
const counts = new Map();
|
|
91
|
+
let total = 0;
|
|
92
|
+
return {
|
|
93
|
+
set(sessionId, pending) {
|
|
94
|
+
if (!sessionId) return;
|
|
95
|
+
const current = counts.get(sessionId) || 0;
|
|
96
|
+
if (pending) {
|
|
97
|
+
counts.set(sessionId, current + 1);
|
|
98
|
+
total += 1;
|
|
99
|
+
} else if (current > 0) {
|
|
100
|
+
if (current === 1) counts.delete(sessionId);
|
|
101
|
+
else counts.set(sessionId, current - 1);
|
|
102
|
+
total -= 1;
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
hasAny: () => total > 0,
|
|
106
|
+
has: (sessionId) => (counts.get(sessionId) || 0) > 0,
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
export const openAttentionDestination = async ({ api, activator, controller, sessionId, eventKey, setNavigationPending } = {}) => {
|
|
110
|
+
try { setNavigationPending?.(sessionId, true); } catch {}
|
|
111
|
+
try {
|
|
112
|
+
let result;
|
|
113
|
+
try { result = await activator?.activate?.(sessionId); } catch { result = null; }
|
|
114
|
+
const opened = result?.ok === true && result?.verified === true;
|
|
115
|
+
if (opened) {
|
|
116
|
+
controller?.acknowledge?.(sessionId, eventKey);
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
api?.ui?.toast?.({
|
|
121
|
+
title: "Work Context",
|
|
122
|
+
message: "The target session could not be opened. Attention remains unread.",
|
|
123
|
+
variant: "warning",
|
|
124
|
+
duration: 5000,
|
|
125
|
+
});
|
|
126
|
+
} catch {}
|
|
127
|
+
return false;
|
|
128
|
+
} finally {
|
|
129
|
+
try { setNavigationPending?.(sessionId, false); } catch {}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
89
132
|
|
|
90
133
|
const validAttention = (value) => value
|
|
91
134
|
&& typeof value === "object"
|
|
@@ -260,7 +303,7 @@ export const desktopNotificationsEnabled = (projectRoot) => {
|
|
|
260
303
|
try { return loadConfig(projectRoot).notifications?.desktop !== false; } catch { return false; }
|
|
261
304
|
};
|
|
262
305
|
|
|
263
|
-
export const createAttentionTuiController = ({ api, projectRoot, read = readWorkContextSnapshot, onAttention, isFocused = () => true, now } = {}) => {
|
|
306
|
+
export const createAttentionTuiController = ({ api, projectRoot, read = readWorkContextSnapshot, onAttention, isFocused = () => true, shouldAcknowledge = () => true, now } = {}) => {
|
|
264
307
|
const persisted = readTuiState(projectRoot).attention;
|
|
265
308
|
const engine = createAttentionEngine({
|
|
266
309
|
persisted,
|
|
@@ -271,6 +314,10 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
|
|
|
271
314
|
let snapshot = null;
|
|
272
315
|
let disposed = false;
|
|
273
316
|
let pending = Promise.resolve();
|
|
317
|
+
const acknowledgeObserved = (sessionId) => {
|
|
318
|
+
const observedEventKey = engine.attentionFor(sessionId)?.eventKey;
|
|
319
|
+
return observedEventKey ? engine.acknowledge(sessionId, observedEventKey) : false;
|
|
320
|
+
};
|
|
274
321
|
const refresh = async () => {
|
|
275
322
|
try {
|
|
276
323
|
const result = await read({ projectRoot, sessionId: currentSessionId(api) });
|
|
@@ -278,7 +325,7 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
|
|
|
278
325
|
linked = linkedSessionIds(result);
|
|
279
326
|
snapshot = result.data;
|
|
280
327
|
const current = currentSessionId(api);
|
|
281
|
-
if (isFocused() !== false && current && linked.has(current))
|
|
328
|
+
if (isFocused() !== false && current && linked.has(current) && shouldAcknowledge(current) !== false) acknowledgeObserved(current);
|
|
282
329
|
}
|
|
283
330
|
} catch {}
|
|
284
331
|
return linked;
|
|
@@ -290,7 +337,7 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
|
|
|
290
337
|
await refresh();
|
|
291
338
|
if (!linked.has(sessionId)) return { changed: false, unlinked: true };
|
|
292
339
|
const foreground = isFocused() !== false ? currentSessionId(api) : undefined;
|
|
293
|
-
if (foreground === sessionId)
|
|
340
|
+
if (foreground === sessionId && shouldAcknowledge(sessionId) !== false) acknowledgeObserved(sessionId);
|
|
294
341
|
const result = engine.apply(event, { foreground });
|
|
295
342
|
if (result.changed) onAttention?.({
|
|
296
343
|
sessionId,
|
|
@@ -306,7 +353,7 @@ export const createAttentionTuiController = ({ api, projectRoot, read = readWork
|
|
|
306
353
|
pending = result.catch(() => {});
|
|
307
354
|
return result;
|
|
308
355
|
};
|
|
309
|
-
const acknowledge = (sessionId, observedEventKey) => engine.acknowledge(sessionId, observedEventKey);
|
|
356
|
+
const acknowledge = (sessionId, observedEventKey) => disposed ? false : engine.acknowledge(sessionId, observedEventKey);
|
|
310
357
|
const aggregate = (matches) => {
|
|
311
358
|
const bySession = new Map();
|
|
312
359
|
const current = currentSessionId(api);
|
|
@@ -346,6 +393,8 @@ export const tui = async (api, options = {}) => {
|
|
|
346
393
|
const activator = options.attentionActivator
|
|
347
394
|
|| (typeof api.route?.navigate === "function" ? createAttentionActivator({ api, ...options.activatorOptions }) : null);
|
|
348
395
|
let controller;
|
|
396
|
+
const notificationNavigations = createPendingNavigationTracker();
|
|
397
|
+
const setNavigationPending = (sessionId, pending) => notificationNavigations.set(sessionId, pending);
|
|
349
398
|
const globalChannel = options.globalAttentionChannel === false
|
|
350
399
|
? null
|
|
351
400
|
: options.globalAttentionChannel || (typeof api.ui?.toast === "function" ? createGlobalAttentionChannel(options.globalAttentionOptions) : null);
|
|
@@ -361,7 +410,8 @@ export const tui = async (api, options = {}) => {
|
|
|
361
410
|
globalChannel?.activity?.();
|
|
362
411
|
void activator?.capture?.();
|
|
363
412
|
const sessionId = currentSessionId(api);
|
|
364
|
-
|
|
413
|
+
const observedEventKey = sessionId && !notificationNavigations.hasAny() ? controller?.attentionFor(sessionId)?.eventKey : null;
|
|
414
|
+
if (observedEventKey) controller?.acknowledge(sessionId, observedEventKey);
|
|
365
415
|
},
|
|
366
416
|
onBlur: () => {
|
|
367
417
|
globalChannel?.deactivate?.();
|
|
@@ -375,6 +425,7 @@ export const tui = async (api, options = {}) => {
|
|
|
375
425
|
isFocused: options.isTuiFocused || (globalDelivery
|
|
376
426
|
? () => globalChannel.hasActiveInstance() ? globalChannel.isActive() && focus.isFocused() : focus.isFocused()
|
|
377
427
|
: () => focus.isFocused()),
|
|
428
|
+
shouldAcknowledge: () => !notificationNavigations.hasAny(),
|
|
378
429
|
onAttention: (change) => {
|
|
379
430
|
try { options.onAttention?.(change); } catch {}
|
|
380
431
|
const context = change.contexts?.[0];
|
|
@@ -386,7 +437,14 @@ export const tui = async (api, options = {}) => {
|
|
|
386
437
|
workspaceTitle: context.workspaceTitle,
|
|
387
438
|
stageTitle: context.stageTitle,
|
|
388
439
|
});
|
|
389
|
-
const onOpen = activator?.available ? () =>
|
|
440
|
+
const onOpen = activator?.available ? () => openAttentionDestination({
|
|
441
|
+
api,
|
|
442
|
+
activator,
|
|
443
|
+
controller,
|
|
444
|
+
sessionId: change.sessionId,
|
|
445
|
+
eventKey: change.attention.eventKey,
|
|
446
|
+
setNavigationPending,
|
|
447
|
+
}) : undefined;
|
|
390
448
|
void Promise.resolve(desktopNotifier.notify(context, { onOpen })).catch(() => {});
|
|
391
449
|
},
|
|
392
450
|
now: options.now,
|
|
@@ -396,7 +454,8 @@ export const tui = async (api, options = {}) => {
|
|
|
396
454
|
registrations.push(api.event.on("tui.session.select", (event) => {
|
|
397
455
|
queueMicrotask(() => {
|
|
398
456
|
const sessionId = currentSessionId(api);
|
|
399
|
-
|
|
457
|
+
const observedEventKey = sessionId && !notificationNavigations.hasAny() ? controller.attentionFor(sessionId)?.eventKey : null;
|
|
458
|
+
if (observedEventKey) controller.acknowledge(sessionId, observedEventKey);
|
|
400
459
|
});
|
|
401
460
|
}));
|
|
402
461
|
let cleaned = false;
|
package/src/core.js
CHANGED
|
@@ -21,8 +21,20 @@ const stageBody = (record, title, goal, prompt = record.data.prompt || "") => {
|
|
|
21
21
|
return `${body(title, goal, prompt).trimEnd()}${result}${reopenHistory}${archiveHistory}`;
|
|
22
22
|
};
|
|
23
23
|
const stageResult = (record) => record.body.match(/\n## Result\s*\n([\s\S]*?)(?=\n## (?:Reopen|Archive) History|$)/)?.[1]?.trim() ?? null;
|
|
24
|
+
const preservedStageResult = (record) => stageResult(record)
|
|
25
|
+
|| [...(record.data.reopen_history || [])].reverse().find((entry) => entry.previous_result)?.previous_result
|
|
26
|
+
|| null;
|
|
24
27
|
const appendHistory = (bodyText, heading, entry) => `${bodyText.trimEnd()}${bodyText.includes(`\n## ${heading}\n`) ? "" : `\n\n## ${heading}\n`}\n- ${entry}\n`;
|
|
25
28
|
const automaticFinishAllowed = (storage, workspace) => /(?:^|\n)AUTO_STAGE_FINISH:\s*allowed\s*$/mi.test(storage.readStage(workspace, "01").data.prompt || "");
|
|
29
|
+
const resumeConfirmationRequired = (prompt) => /(?:^|\r?\n)RESUME_CONFIRMATION: required(?=\r?\n|$)/.test(prompt || "");
|
|
30
|
+
const resumePresentationInstruction = ({ confirmationRequired }) => `Before doing any work, give the user a concise context summary:
|
|
31
|
+
- Use the user's language.
|
|
32
|
+
- Name the stage without reporting workspace IDs, stage IDs, session UUIDs, ordinals, ok flags, or absent error codes.
|
|
33
|
+
- Add a short "Goal" section that restates presentation.goal in plain, non-technical language.
|
|
34
|
+
- When presentation.scope contains several clear deliverables, add "In this stage we will" with 2-5 short outcome-oriented bullets. Derive them only from the saved prompt, previous result, and workspace knowledge; do not invent scope. Omit this block for a small stage.
|
|
35
|
+
- Mention previous progress only when presentation.previous_result or presentation.previous_session_summary contains useful information.
|
|
36
|
+
- State the immediate next action in one sentence.
|
|
37
|
+
${confirmationRequired ? "- Ask for the explicitly required confirmation and wait before inspecting or changing application code." : "- Then continue with the work immediately. Do not ask for generic confirmation; ask a focused question only when an unresolved decision genuinely blocks progress."}`;
|
|
26
38
|
const assertNoSymlinkPath = (file) => { let current = path.parse(file).root; for (const part of file.slice(current.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { if (fs.lstatSync(current).isSymbolicLink()) fail(ERROR_CODES.STORAGE_ERROR, `Symlink path component is not supported: ${current}`); } catch (error) { if (error.code !== "ENOENT") throw error; break; } } };
|
|
27
39
|
|
|
28
40
|
function parseIssue(url) {
|
|
@@ -266,8 +278,14 @@ export class WorkContext {
|
|
|
266
278
|
this.writeEvents([event("session.started", workspace, stage, ordinal, sessionId, actor(this.options), { summary: options.summary || "continued work", opencode_session_id: options.opencodeSessionId || null, branch: options.branch || null })]);
|
|
267
279
|
generateProjections(this.storage);
|
|
268
280
|
const previousSession = previous.at(-1) || null;
|
|
281
|
+
const previousSessionSummary = previousSession?.summary && previousSession.summary !== "continued work"
|
|
282
|
+
? previousSession.summary
|
|
283
|
+
: null;
|
|
269
284
|
const firstResume = previous.length === 0;
|
|
270
285
|
const hasPrompt = Boolean(stageRecord.data.prompt?.trim());
|
|
286
|
+
const confirmationRequired = hasPrompt && resumeConfirmationRequired(stageRecord.data.prompt);
|
|
287
|
+
const previousResult = preservedStageResult(stageRecord);
|
|
288
|
+
const workspaceTitle = this.storage.readWorkspace(workspace).data.title;
|
|
271
289
|
const workspaceKnowledge = activeKnowledge(this.listKnowledge(workspace).data);
|
|
272
290
|
const automaticFinish = automaticFinishAllowed(this.storage, workspace);
|
|
273
291
|
return this.result({
|
|
@@ -282,22 +300,27 @@ export class WorkContext {
|
|
|
282
300
|
first: firstResume,
|
|
283
301
|
summary: firstResume
|
|
284
302
|
? `Starting work on stage ${stage}: ${stageRecord.data.title}.`
|
|
285
|
-
: `Continuing work on stage ${stage}: ${stageRecord.data.title}. Last recorded summary: ${
|
|
303
|
+
: `Continuing work on stage ${stage}: ${stageRecord.data.title}. Last recorded summary: ${previousSessionSummary || previousResult || "no saved report"}.`,
|
|
286
304
|
last_session_summary: previousSession?.summary || null,
|
|
305
|
+
presentation: {
|
|
306
|
+
workspace_title: workspaceTitle,
|
|
307
|
+
stage_title: stageRecord.data.title,
|
|
308
|
+
goal: stageRecord.data.goal || stageRecord.data.title,
|
|
309
|
+
scope: stageRecord.data.prompt || null,
|
|
310
|
+
previous_result: previousResult,
|
|
311
|
+
previous_session_summary: previousSessionSummary,
|
|
312
|
+
},
|
|
287
313
|
context: {
|
|
288
314
|
essence: stageRecord.data.goal || stageRecord.data.title,
|
|
289
|
-
previous:
|
|
315
|
+
previous: previousSessionSummary || previousResult || "No previous progress was recorded.",
|
|
290
316
|
now: hasPrompt ? stageRecord.data.prompt : "First clarify the task and work plan with the user.",
|
|
291
317
|
workspace_knowledge: workspaceKnowledge,
|
|
292
318
|
lifecycle: { automatic_finish_allowed: automaticFinish },
|
|
293
319
|
},
|
|
294
|
-
next_action: hasPrompt ?
|
|
320
|
+
next_action: hasPrompt ? confirmationRequired ? "await_confirmation" : "start_work" : "ask_questions",
|
|
295
321
|
instruction: `${hasPrompt
|
|
296
|
-
?
|
|
297
|
-
|
|
298
|
-
|| `Review stage ${stage}: ${stageRecord.data.title} and begin work only after confirming there are no unanswered questions.`
|
|
299
|
-
: `Stage ${stage}: ${stageRecord.data.title} was resumed before. Report the context and wait for the user's confirmation before continuing work.`
|
|
300
|
-
: `Stage ${stage}: ${stageRecord.data.title} has no non-empty prompt. Do not start implementation; ask the user the questions needed to define the work.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
|
|
322
|
+
? `${resumePresentationInstruction({ confirmationRequired })}\n\nSaved working prompt:\n${stageRecord.data.prompt}`
|
|
323
|
+
: `This stage has no non-empty prompt. Give the user a concise plain-language summary of the stage title and goal, then ask focused questions needed to define the intended outcome and scope. Do not inspect or modify application code yet. Do not report raw operation metadata or identifiers.`}\n\nDo not invoke stage finish unless the user explicitly requests the lifecycle command. Automatic completion is permitted only when lifecycle.automatic_finish_allowed is true, which requires the exact AUTO_STAGE_FINISH: allowed line in this workspace's Planning-stage prompt.`,
|
|
301
324
|
},
|
|
302
325
|
}, [workspace, stage]);
|
|
303
326
|
});
|
package/src/tool-definitions.js
CHANGED
|
@@ -61,7 +61,7 @@ export const work_context_create_workspace = tool({ description: "Create a works
|
|
|
61
61
|
const currentSession = ctx.sessionByOpenCodeId(oc.sessionID);
|
|
62
62
|
return ctx.createWorkspace(a.title, { sessionId: randomUUID(), ...(currentSession ? {} : { opencodeSessionId: oc.sessionID }) });
|
|
63
63
|
}) });
|
|
64
|
-
export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its prompt
|
|
64
|
+
export const work_context_start_session = tool({ description: "Start a new active session for a stage and return its human-oriented presentation, prompt, and active workspace knowledge.", args: { ...common, summary: tool.schema.string().optional() }, execute: run((ctx, a, oc) => ctx.startSession(a.workspace, a.stage, { sessionId: randomUUID(), opencodeSessionId: oc.sessionID, summary: a.summary, takeover: true })) });
|
|
65
65
|
export const work_context_add_stage = tool({ description: "Add a stage; when the current OpenCode session is not associated with a workspace, enter the new stage in that session immediately.", args: { workspace: tool.schema.string().optional(), title: tool.schema.string(), goal: tool.schema.string().optional(), prompt: tool.schema.string().optional(), dependsOn: tool.schema.array(tool.schema.string()).optional() }, execute: run(addStageFromTool) });
|
|
66
66
|
export const work_context_rename_stage = tool({ description: "Rename a stage while preserving its ID and history; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, title: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.renameStage(workspace, stageFromSession(ctx, workspace, a.stage), a.title); }) });
|
|
67
67
|
export const work_context_update_stage = tool({ description: "Update an existing stage description; workspace and stage can be omitted in the current OpenCode session.", args: { ...contextualStage, description: tool.schema.string() }, execute: run((ctx, a) => { const workspace = workspaceFromSession(ctx, a.workspace); return ctx.updateStage(workspace, stageFromSession(ctx, workspace, a.stage), a.description); }) });
|