gsd-for-omp 1.1.1 → 1.1.3

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/CHANGELOG.md CHANGED
@@ -4,6 +4,24 @@ All notable changes to `gsd-for-omp` are recorded here in [Keep a Changelog](htt
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [1.1.3] - 2026-10-26
8
+
9
+ ### Added
10
+
11
+ - `/gsd-execute-phase` checks that OMP will offer isolated tasks before the run starts. Without `--interactive`, it stops with a message when `task.isolation.enabled` is off or plan mode hides the task `isolated` option, instead of failing at the first executor dispatch after state reads and config writes. When nothing configures `task.isolation.enabled` (no user, project, env or protocol-host value), it is turned on for the current session only and a notification says so; `config.yml` is not touched. OMP 17 does not expose tool schemas to extensions, so it starts the run unchecked as before. The generated `extensions/gsd-for-omp.ts` wrapper now passes OMP's settings registry to the extension, so run `gsd-for-omp install` after updating.
12
+
13
+ ### Fixed
14
+
15
+ - The native phase execution guard no longer blocks writes that cannot touch the parent checkout: OMP settings and session URLs (`cfg://`, `local://`, `agent://`, `proc://`, `artifact://`, `skill://`, `omp://`, `history://`), `~/` paths, and files outside the Git checkout, such as `~/.omp/agent/config.yml` or another repository. Hashline, `apply_patch` and `sloppy` edits are now checked against the files named in their payload, including move destinations, so `.planning/` edits pass and any source target blocks the call; previously every edit without a `path` field was blocked. `write xd://<tool>` is checked as a call to `<tool>`, so `xd://gsd_invoke` passes and `xd://ast_edit` on source files still blocks. Unknown targets, unknown URL schemes, and outside paths that resolve into the checkout through a symlink stay blocked.
16
+ - The phase execution guard is released when the agent run ends with no native GSD task running and either no task was ever dispatched or the last `[checkpoint]` line reported `failed`. Before, a stale `status: executing` in `STATE.md` kept the guard on for the rest of the session after a run stopped early.
17
+ - Projected `gsd-executor` agents create a per-agent `agent-phase{PHASE}-plan{PLAN}` branch before their first commit when HEAD is detached. OMP isolated workspaces start with a detached HEAD, which made the executor's commit safety check refuse every task commit. OMP captures the commits from HEAD in both patch and branch merge modes, and the branch never leaves the isolated workspace.
18
+
19
+ ## [1.1.2] - 2026-10-21
20
+
21
+ ### Added
22
+
23
+ - In GSD projects, OMP now tells you when a newer `gsd-for-omp` is on npm: one notification per session (in the project's `response_language`) and a `⬆ <version>` marker in the GSD footer. The registry lookup (`npm view gsd-for-omp version`) runs in the background at most once a day, is cached in `~/.cache/gsd-for-omp/update-check.json` (or under `XDG_CACHE_HOME`), and fails silently. The same notice asks for `gsd-for-omp install` when the package was upgraded but the OMP files were not re-projected. The suggested command always carries a shell-quoted `--root` for the session's runtime root, so it also works for custom roots from a terminal without `PI_CODING_AGENT_DIR`. Set `GSD_FOR_OMP_NO_UPDATE_CHECK=1` or `NO_UPDATE_NOTIFIER=1` to turn it off; it is also off when `CI` is set.
24
+
7
25
  ## [1.1.1] - 2026-10-21
8
26
 
9
27
  ### Security
@@ -90,7 +108,9 @@ Related: [PR #53](https://github.com/tchivs/gsd-omp/pull/53), [release PR #54](h
90
108
 
91
109
  Related: [PR #51](https://github.com/tchivs/gsd-omp/pull/51), [release PR #52](https://github.com/tchivs/gsd-omp/pull/52).
92
110
 
93
- [Unreleased]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.1...HEAD
111
+ [Unreleased]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.3...HEAD
112
+ [1.1.3]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.2...v1.1.3
113
+ [1.1.2]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.1...v1.1.2
94
114
  [1.1.1]: https://github.com/GManzato/gsd-for-omp/compare/v1.1.0...v1.1.1
95
115
  [1.1.0]: https://github.com/GManzato/gsd-for-omp/compare/v1.0.27...v1.1.0
96
116
  [1.0.27]: https://github.com/GManzato/gsd-for-omp/compare/v1.0.26...v1.0.27
package/README.md CHANGED
@@ -50,8 +50,10 @@ The `gsd_invoke` tool gives agents structured access to the same `gsd-tools` CLI
50
50
  ## OMP integration
51
51
 
52
52
  - **Status overlay** — `Ctrl+Shift+G` opens a live GSD status overlay (also available at startup with the `--gsd-status` flag); a widget and footer show the same state.
53
+ - **Update notice** — in GSD projects, a notification and a `⬆` footer marker appear when a newer `gsd-for-omp` is published; the npm check runs in the background at most once a day. Opt out with `GSD_FOR_OMP_NO_UPDATE_CHECK=1`.
53
54
  - **Native controls** — `/gsd-status` accepts `--compact`, `--stop`, `--branch`, `--tree`, `--switch`, and `--reload` for OMP's native session controls.
54
55
  - **Goal Mode** — when the host emits `goal_updated`, the objective, status, and token budget are mirrored in `/gsd-status`; pause or drop the goal (`/goal pause`, `/goal drop`) before `/gsd-next`. Hosts without it, such as OMP 17, keep everything else.
56
+ - **Phase execution** — `/gsd-execute-phase` dispatches executors as isolated OMP tasks, so it needs `task.isolation.enabled: true` with plan mode off (`--interactive` runs inline without it). When the setting is not configured anywhere, it is turned on for the session; an explicit `false` is respected. See [Configuration](docs/CONFIGURATION.md#phase-execution-and-task-isolation).
55
57
  - **Models** — OMP owns the model. Switch with OMP's `/model`; the GSD `model_profile` setting has no effect under OMP. See [Configuration](docs/CONFIGURATION.md#model-routing).
56
58
 
57
59
  ## Update and uninstall
package/README.zh-CN.md CHANGED
@@ -50,8 +50,10 @@ gsd-for-omp doctor
50
50
  ## OMP 集成
51
51
 
52
52
  - **状态 overlay** —— `Ctrl+Shift+G` 打开实时 GSD 状态 overlay(也可在启动时用 `--gsd-status` flag 打开);widget 与 footer 显示同样的状态。
53
+ - **更新提示** —— 在 GSD 项目中,当 npm 上发布了更新的 `gsd-for-omp` 时,会弹出通知并在页脚显示 `⬆` 标记;npm 检查在后台运行,每天最多一次。设置 `GSD_FOR_OMP_NO_UPDATE_CHECK=1` 可关闭。
53
54
  - **原生控制** —— `/gsd-status` 接受 `--compact`、`--stop`、`--branch`、`--tree`、`--switch`、`--reload`,对应 OMP 的原生会话控制。
54
55
  - **Goal Mode** —— 当主机提供 `goal_updated` 事件时,目标、状态与 token 预算会同步到 `/gsd-status`;运行 `/gsd-next` 前请先暂停或放弃目标(`/goal pause`、`/goal drop`)。没有该事件的主机(如 OMP 17)仍可使用其余全部功能。
56
+ - **阶段执行** —— `/gsd-execute-phase` 以 OMP 隔离任务派发执行器,因此需要 `task.isolation.enabled: true` 且关闭计划模式(`--interactive` 在当前会话内顺序执行,不需要隔离)。若该设置在任何位置都未配置,会为当前会话启用;显式的 `false` 会被保留。详见[配置参考](docs/CONFIGURATION.md#phase-execution-and-task-isolation)。
55
57
  - **模型** —— 模型由 OMP 掌管。请使用 OMP 的 `/model` 切换;GSD 的 `model_profile` 设置在 OMP 下不起作用。详见[配置参考](docs/CONFIGURATION.md#model-routing)。
56
58
 
57
59
  ## 更新与卸载
@@ -320,9 +320,27 @@ function assertSupportedCore(coreRoot) {
320
320
  return corePackage.version;
321
321
  }
322
322
 
323
+ // The settings registry subpath only resolves inside the OMP extension graph,
324
+ // so the wrapper imports it and hands it to the CommonJS extension. Hosts
325
+ // without the registry (OMP before 18.3) load the extension without it.
323
326
  function extensionWrapper(root) {
324
327
  const extensionPath = path.join(__dirname, '..', 'src', 'extension.cjs');
325
- return `import { createRequire } from "node:module";\n\nconst require = createRequire(import.meta.url);\nconst extension = require(${JSON.stringify(extensionPath)});\n\nexport default (pi: unknown) => extension(pi, { runtime: "omp", runtimeRoot: ${JSON.stringify(root)} });\n`;
328
+ return [
329
+ 'import { createRequire } from "node:module";',
330
+ '',
331
+ 'const require = createRequire(import.meta.url);',
332
+ `const extension = require(${JSON.stringify(extensionPath)});`,
333
+ '',
334
+ 'let settingsRegistry: unknown;',
335
+ 'try {',
336
+ ' settingsRegistry = await import("@oh-my-pi/pi-coding-agent/config/registry");',
337
+ '} catch {',
338
+ ' settingsRegistry = undefined;',
339
+ '}',
340
+ '',
341
+ `export default (pi: unknown) => extension(pi, { runtime: "omp", runtimeRoot: ${JSON.stringify(root)}, settingsRegistry });`,
342
+ '',
343
+ ].join('\n');
326
344
  }
327
345
 
328
346
  function desiredArtifacts(root, coreRoot) {
@@ -60,7 +60,7 @@ An install performs these steps:
60
60
 
61
61
  1. Resolve `@opengsd/gsd-core` and run `Eos.initialize()`.
62
62
  2. Reject a bundled GSD Core version below the minimum declared in `package.json` `engines.gsd` (currently `>=1.12.0`).
63
- 3. Build `extensions/gsd-for-omp.ts`, a thin OMP module wrapper that imports `src/extension.cjs` and passes `{ runtime: "omp", runtimeRoot }`.
63
+ 3. Build `extensions/gsd-for-omp.ts`, a thin OMP module wrapper that imports `src/extension.cjs` and passes `{ runtime: "omp", runtimeRoot, settingsRegistry }`. `settingsRegistry` is OMP's `@oh-my-pi/pi-coding-agent/config/registry` module, which resolves only inside the extension graph; the wrapper imports it in a `try` block so hosts without it still load.
64
64
  4. Project every `gsd-*.md` agent and every `gsd-*` skill with a `SKILL.md` from the resolved core tree.
65
65
  5. Stage all files in a temporary transaction directory, replace prior targets only after ownership checks, and write `.gsd-for-omp-manifest.json`.
66
66
  6. Remove unchanged stale managed projections and recognized legacy CJS extensions. Modified stale files remain protected.
@@ -139,6 +139,7 @@ Lifecycle event handling is project-scoped (the extension first checks whether t
139
139
  - `auto_compaction_start/end`, `auto_retry_start/end`, and `session_stop` expose transient native runtime signals in status.
140
140
  - `message_end` extracts pending next-action/checkpoint records from assistant text and persists them in the planning workspace.
141
141
  - `tool_execution_start/update/end`, `tool_result`, and `tool_call` track native GSD task IDs, progress, failures, settlement, hook decisions, and guarded repository writes.
142
+ - `turn_end` and `agent_end` release the native phase execution guard: `turn_end` when `STATE.md` no longer reports an executing phase, `agent_end` when the run stopped with no native GSD task running and nothing was dispatched or the last plan failed.
142
143
  - `session_shutdown` clears context and project runtime tracking.
143
144
 
144
145
  ## Status surface and optional Goal Mode adapter
@@ -52,6 +52,10 @@ The extension passes `GSD_AGENTS_DIR` together with `GSD_RUNTIME=omp` to every `
52
52
  | `LC_ALL` | Optional | Next POSIX locale or `en` | First POSIX fallback after `GSD_FOR_OMP_LOCALE`. |
53
53
  | `LC_MESSAGES` | Optional | Next POSIX locale or `en` | Second POSIX fallback after `GSD_FOR_OMP_LOCALE` and `LC_ALL`. |
54
54
  | `LANG` | Optional | `en` | Final POSIX locale fallback after `GSD_FOR_OMP_LOCALE`, `LC_ALL`, and `LC_MESSAGES`. |
55
+ | `GSD_FOR_OMP_NO_UPDATE_CHECK` | Optional | unset | Any value other than empty, `0`, `false`, `no`, or `off` disables the in-session update notice and its background `npm view gsd-for-omp version` lookup. |
56
+ | `NO_UPDATE_NOTIFIER` | Optional | unset | Conventional opt-out honored the same way as `GSD_FOR_OMP_NO_UPDATE_CHECK`. |
57
+ | `CI` | Optional | unset | When set to a truthy value, the update notice is skipped so CI never queries the registry. |
58
+ | `XDG_CACHE_HOME` | Optional | `~/.cache` | Parent of `gsd-for-omp/update-check.json`, which caches the last registry result for 24 hours (1 hour after a failed lookup). |
55
59
 
56
60
  The effective shell/EoS locale is selected in this exact order: `GSD_FOR_OMP_LOCALE`, `LC_ALL`, `LC_MESSAGES`, `LANG`. Supported dictionaries are `en` and `zh-CN`; a value such as `zh_CN.UTF-8` selects `zh-CN`, while an unknown or empty value falls back to English. This locale does not override a project's in-session language setting.
57
61
 
@@ -93,6 +97,45 @@ A minimal project-language example is:
93
97
 
94
98
  To select Simplified Chinese explicitly, use `"response_language": "Simplified Chinese"`. The first interactive `session_start` for a GSD project with no `response_language` offers `Simplified Chinese` or `English`; it can also ask for interaction style if `workflow.text_mode` is not already explicit. Projects without an interactive UI do not receive that picker.
95
99
 
100
+ ## Phase execution and task isolation
101
+
102
+ `/gsd-execute-phase` dispatches every executor as an OMP native `task` with `isolated: true`. OMP offers that option only while `task.isolation.enabled` is `true` and plan mode is off, so the command checks the task tool's live schema before it starts a run:
103
+
104
+ | Situation | Result |
105
+ |---|---|
106
+ | Task tool already offers `isolated` | The run starts. |
107
+ | `task.isolation.enabled` is unset in every layer (provenance `default`) | The extension sets a session-only runtime override to `true`, shows a notification, and starts the run. `config.yml` is not written. |
108
+ | `task.isolation.enabled` is `false` in `config.yml`, a project `.omp/config.yml`, an env var, or a protocol-host default (RPC/ACP modes pin it to `false`) | The run does not start; the message asks for `omp config set task.isolation.enabled true`, which OMP reloads live. |
109
+ | `task.isolation.enabled` is `true` but plan mode hides `isolated` | The run does not start; leave plan mode and run the command again. |
110
+ | `--interactive` | No check: the run executes inline without isolated tasks. |
111
+
112
+ To enable isolation permanently:
113
+
114
+ ```yaml
115
+ # ~/.omp/agent/config.yml
116
+ task:
117
+ isolation:
118
+ enabled: true
119
+ ```
120
+
121
+ The check and the session override use OMP 18's tool schemas and settings registry, which the generated `extensions/gsd-for-omp.ts` wrapper imports from `@oh-my-pi/pi-coding-agent/config/registry` and passes to the extension. OMP 17 exposes neither, so the run starts unchecked; on OMP 17, isolation is the `task.isolation.mode` setting, which defaults to `none`.
122
+
123
+ ### Executor commits in isolated workspaces
124
+
125
+ An OMP isolated workspace is a private copy of the repository with HEAD detached at the parent's commit. The projected `gsd-executor` creates an `agent-phase{PHASE}-plan{PLAN}` branch there before its first commit, which satisfies the executor's protected-branch and detached-HEAD checks. OMP captures the commits from HEAD in both `task.isolation.merge` modes (as a patch, or replayed onto `omp/task/<id>`), and the branch is discarded with the workspace. A protected parent branch such as `main` with `branching_strategy: none` therefore does not block executor commits.
126
+
127
+ ### Parent-checkout guard
128
+
129
+ While a non-interactive phase execution is active, the extension blocks `write`, `edit`, `ast_edit` and applying `lsp` calls that would change a file in the parent Git checkout outside the planning directory; repository changes must come from isolated executors. It allows:
130
+
131
+ - files under the planning directory (normally `.planning/`), unless a path component is a symlink;
132
+ - OMP internal URLs that do not address checkout files: `cfg://`, `local://`, `agent://`, `proc://`, `artifact://`, `skill://`, `omp://`, `history://`;
133
+ - paths outside the checkout, including `~/` paths such as `~/.omp/agent/config.yml`, unless they resolve into the checkout through a symlink.
134
+
135
+ Edit payloads are checked against every file they name (hashline `[PATH#TAG]` headers and `MV` destinations, `apply_patch` and `sloppy` file headers, patch-mode renames); one checkout source blocks the whole call. `write xd://<tool>` is checked as a direct call to `<tool>`. Calls with no recognizable target, and other URL schemes, are blocked.
136
+
137
+ The guard ends when `STATE.md` no longer reports an executing phase at the end of a turn, or when the agent run ends with no native GSD task running and either no task was dispatched during the execution or the last `[checkpoint]` line reported `failed`.
138
+
96
139
  ## Installer CLI configuration
97
140
 
98
141
  The executable accepts one command followed by common options:
@@ -145,6 +145,8 @@ gsd-for-omp install
145
145
 
146
146
  The update also upgrades the plugin's bundled GSD Core dependency. It does not update an OMP-managed engine tree; use OMP's own update path for the host itself.
147
147
 
148
+ Inside a GSD project, OMP tells you when an update is available: one notification per session and a `⬆ <version>` marker in the GSD footer. The registry lookup runs in the background at most once a day and never blocks or fails a session. If the package was upgraded with `npm` but `gsd-for-omp install` was not rerun, the same notice asks you to re-project instead (footer `⬆ reinstall`). Set `GSD_FOR_OMP_NO_UPDATE_CHECK=1` to turn it off; see [Configuration](CONFIGURATION.md#runtime-and-localization-variables).
149
+
148
150
  ## Uninstall
149
151
 
150
152
  Remove managed projections before removing the global installer:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gsd-for-omp",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "Oh My Pi host plugin for the GSD Embeddable Orchestration System — extension bindings, slash-command surface, Host-Integration SDK adapter, and optional Goal Mode status integration for AI coding agents",
5
5
  "license": "MIT",
6
6
  "author": "Gilles Manzato",
@@ -8,9 +8,11 @@ const fs = require('node:fs');
8
8
  const path = require('node:path');
9
9
  const { goalStateFromEvent } = require('./goal-mode.cjs');
10
10
  const { extractCheckpoint, extractNextAction, persistCheckpoint, persistNextAction } = require('./planning-store.cjs');
11
+ const { usesChinese } = require('./localize.cjs');
11
12
  const { isGsdProject, stateReminder } = require('./planning.cjs');
12
13
  const { releaseGsdProjectRuntimeState } = require('./state.cjs');
13
14
  const { extractTaskResults, failedNativeTaskResults } = require('./task-results.cjs');
15
+ const { updateNoticeMessage } = require('./update-check.cjs');
14
16
 
15
17
  function assistantMessageText(message) {
16
18
  if (message?.role !== 'assistant' || !Array.isArray(message.content)) return '';
@@ -27,6 +29,7 @@ function registerLifecycleHandlers({
27
29
  pi,
28
30
  runtimeRoot,
29
31
  state,
32
+ cancelUpdateCheck,
30
33
  choosePendingContinuation,
31
34
  forgetGoalModeState,
32
35
  nativePhaseWriteBlock,
@@ -35,13 +38,16 @@ function registerLifecycleHandlers({
35
38
  preToolHookOutcome,
36
39
  queueHookAdvisories,
37
40
  reconcileTaskSettlement,
41
+ recordNativePhaseCheckpoint,
38
42
  releaseFailedGsdTaskRequest,
39
43
  releaseInactiveNativePhase,
40
44
  releaseSettledGsdTasks,
45
+ releaseStoppedNativePhase,
41
46
  rememberGoalModeState,
42
47
  scheduleOnboardingPrompt,
43
48
  setNativeRuntimeSignal,
44
49
  showNativeStatusOverlay,
50
+ startUpdateCheck,
45
51
  startGraphifyAutoUpdate,
46
52
  trackGraphifyHead,
47
53
  trackGsdTaskProgress,
@@ -70,6 +76,10 @@ function registerLifecycleHandlers({
70
76
  if (!ctx.hasUI) return;
71
77
  const reminder = stateReminder(ctx.cwd);
72
78
  if (reminder) ctx.ui.notify(reminder, 'info');
79
+ startUpdateCheck((notice) => {
80
+ ctx.ui.notify(updateNoticeMessage(notice, usesChinese(ctx.cwd)), 'info');
81
+ updateStatus(ctx);
82
+ });
73
83
  });
74
84
 
75
85
  try {
@@ -88,6 +98,7 @@ function registerLifecycleHandlers({
88
98
  }
89
99
 
90
100
  pi.on('session_shutdown', (_event, ctx) => {
101
+ cancelUpdateCheck();
91
102
  forgetGoalModeState(ctx);
92
103
  releaseGsdProjectRuntimeState(state, ctx.cwd);
93
104
  });
@@ -149,12 +160,21 @@ function registerLifecycleHandlers({
149
160
  updateStatus(ctx);
150
161
  });
151
162
 
163
+ // turn_end fires after every model turn, including the ones before the first dispatch;
164
+ // agent_end marks the run handing control back to the user.
165
+ pi.on('agent_end', async (_event, ctx) => {
166
+ if (!isGsdProject(ctx.cwd)) return;
167
+ releaseStoppedNativePhase(ctx.cwd);
168
+ updateStatus(ctx);
169
+ });
170
+
152
171
  pi.on('message_end', async (event, ctx) => {
153
172
  if (!isGsdProject(ctx.cwd)) return;
154
173
  const output = assistantMessageText(event?.message);
155
174
  const checkpoint = extractCheckpoint(output);
156
175
  const nextAction = extractNextAction(output);
157
176
  if (checkpoint) persistCheckpoint(ctx.cwd, checkpoint);
177
+ recordNativePhaseCheckpoint(ctx.cwd, output);
158
178
  if (nextAction) persistNextAction(ctx.cwd, nextAction);
159
179
  if (checkpoint || nextAction) updateStatus(ctx);
160
180
  if (nextAction && ctx.hasUI) await choosePendingContinuation(ctx, nextAction);
@@ -54,6 +54,7 @@ const {
54
54
  const { prioritizeRecentPhase, rememberRecentPhase } = require('./planning-store.cjs');
55
55
  const { isGsdProject } = require('./planning.cjs');
56
56
  const { parseCommandLine } = require('./util.cjs');
57
+ const { ensureTaskIsolation, taskIsolationMessage } = require('./task-isolation.cjs');
57
58
 
58
59
  /**
59
60
  * Native workflow launchers bound to the host API and runtime paths.
@@ -127,10 +128,12 @@ function createNativeLaunchers({ pi, options, agentsDir, cliPath, state }) {
127
128
  });
128
129
  }
129
130
  const phase = parseCommandLine(input)[0];
131
+ const interactive = parseCommandLine(input).includes('--interactive');
132
+ if (!interactive && !(await requireTaskIsolation(ctx))) return;
130
133
  rememberRecentPhase(ctx.cwd, 'execute', phase);
131
134
  await nameNativePhaseSession(ctx, phase, 'execute');
132
135
  const projectPath = path.resolve(ctx.cwd);
133
- nativePhaseExecutions.set(projectPath, { interactive: parseCommandLine(input).includes('--interactive') });
136
+ nativePhaseExecutions.set(projectPath, { interactive, dispatched: false });
134
137
  try {
135
138
  await pi.sendMessage({ customType: 'gsd-native-execute-phase', content: prompt, display: true }, { triggerTurn: true });
136
139
  } catch (error) {
@@ -139,6 +142,25 @@ function createNativeLaunchers({ pi, options, agentsDir, cliPath, state }) {
139
142
  }
140
143
  }
141
144
 
145
+ // Non-interactive execution dispatches every executor as an isolated native task; refuse
146
+ // before the run starts writing state rather than after the first dispatch fails.
147
+ async function requireTaskIsolation(ctx) {
148
+ const chinese = usesChinese(ctx.cwd);
149
+ const isolation = ensureTaskIsolation(pi, options.settingsRegistry);
150
+ if (isolation.enabled && typeof ctx.ui?.notify === 'function') {
151
+ ctx.ui.notify(chinese
152
+ ? '已为本会话启用 OMP 任务隔离(task.isolation.enabled 未配置)。'
153
+ : 'Enabled OMP task isolation for this session (task.isolation.enabled was not configured).', 'info');
154
+ }
155
+ if (isolation.available) return true;
156
+ await pi.sendMessage({
157
+ customType: 'gsd-execute-isolation-required',
158
+ content: taskIsolationMessage(isolation.reason, chinese),
159
+ display: true,
160
+ }, { triggerTurn: false });
161
+ return false;
162
+ }
163
+
142
164
  async function chooseExecutionPhase(ctx) {
143
165
  const chinese = usesChinese(ctx.cwd);
144
166
  const phases = prioritizeRecentPhase(ctx.cwd, 'execute', executablePhaseOptions(ctx.cwd));
@@ -40,7 +40,7 @@ function nativeTaskActivityLines(count, chinese) {
40
40
  * Per-instance native task tracker over the shared runtime state: ref-counted task ids, task calls and live execution progress.
41
41
  */
42
42
  function createNativeTaskTracker({ state }) {
43
- const { activeGsdTaskIds, activeGsdTaskIdsByCall, activeGsdTaskRefCounts, nativeTaskExecutionByCall } = state;
43
+ const { activeGsdTaskIds, activeGsdTaskIdsByCall, activeGsdTaskRefCounts, nativePhaseExecutions, nativeTaskExecutionByCall } = state;
44
44
 
45
45
  function taskIdsFor(cwd) {
46
46
  const projectPath = path.resolve(cwd);
@@ -163,6 +163,8 @@ function createNativeTaskTracker({ state }) {
163
163
  if (event?.toolName !== 'task' || typeof event.toolCallId !== 'string' || !event.toolCallId) return;
164
164
  const execution = nativeTaskExecutionState(cwd, event, null);
165
165
  if (!execution) return;
166
+ const phaseExecution = nativePhaseExecutions.get(path.resolve(cwd));
167
+ if (phaseExecution) phaseExecution.dispatched = true;
166
168
  trackGsdTaskRequest(event, cwd);
167
169
  }
168
170
 
@@ -45,7 +45,7 @@ const nativeMessageTypes = new Set([
45
45
  'gsd-continuation', 'gsd-continuation-deferred', 'gsd-continuation-dismissed',
46
46
  'gsd-continuation-error', 'gsd-continuation-preview', 'gsd-native-continuation',
47
47
  'gsd-native-skill-command', 'gsd-native-tasks-active', 'gsd-native-abort', 'gsd-native-compact', 'gsd-native-session', 'gsd-goal-mode-active', 'gsd-projected-skill-input-error', 'gsd-ship-ready', 'gsd-resume-ready',
48
- 'gsd-workflow-advisory', 'gsd-hook-advisory',
48
+ 'gsd-workflow-advisory', 'gsd-hook-advisory', 'gsd-execute-isolation-required',
49
49
  ]);
50
50
 
51
51
  for (const name of nativeMessageWorkflowNames) {
@@ -5,23 +5,125 @@
5
5
  */
6
6
 
7
7
  const fs = require('node:fs');
8
+ const os = require('node:os');
8
9
  const path = require('node:path');
9
10
  const { resolvedPlanningPaths, stateSnapshot } = require('./planning.cjs');
10
11
 
11
- function nativeMutationPaths(event) {
12
- const input = event?.input || {};
13
- if (['edit', 'write'].includes(event?.toolName)) return [input.path || input.filePath || input.file_path || input.file || ''];
14
- if (['ast_edit', 'ast-edit'].includes(event?.toolName)) return Array.isArray(input.paths) && input.paths.length ? input.paths : [input.path || ''];
15
- if (event?.toolName === 'lsp' && (['rename', 'rename_file'].includes(input.action) || (input.action === 'code_actions' && input.apply === true))) {
16
- const paths = [input.file || input.path || '', input.new_name || input.newName || ''];
17
- if (input.action === 'code_actions' && Array.isArray(input.edits)) {
18
- for (const edit of input.edits) paths.push(edit?.file || edit?.path || '');
12
+ // OMP internal URLs that address settings, session artifacts, agents or jobs, never a checkout file.
13
+ const NON_CHECKOUT_URL = /^(?:cfg|local|agent|proc|artifact|skill|omp|history):\/\//i;
14
+ const URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
15
+ // `write xd://<tool>` runs <tool> with the JSON `content` as its arguments, without a tool_call of its own.
16
+ const XD_DEVICE = /^xd:\/\/([^/?#\s]+)\/?$/i;
17
+ const CHECKPOINT_STATUS = /^\s*\[checkpoint\]\s+phase\s+\S+\s+wave\s+\d+\/\d+\s+plan\s+\S+\s+([a-z]+)/gmi;
18
+
19
+ // Edit payload grammars that carry their targets inside `input`.
20
+ const SLOPPY_TARGET = /^\s*\*\*\*\s+Edit\s+File:\s*(.+?)(?:\s+all)?\s*$/;
21
+ const APPLY_PATCH_TARGET = /^\s*\*\*\*\s+(?:(?:Add|Update|Delete)\s+File|Move\s+to):\s*(.+?)\s*$/;
22
+ // Hashline `[PATH#TAG]` (tag optional), legacy `¶PATH#TAG`, and `MV DEST` file operations.
23
+ const HASHLINE_TARGET = /^\s*(?:\[(.+?)(?:#[^#\]]*)?\]|¶+(.+?)(?:#[^#\s]*)?|MV\s+(.+?))\s*$/;
24
+
25
+ function unquote(value) {
26
+ return value.replace(/^(["'])(.*)\1$/, '$2');
27
+ }
28
+
29
+ function editPayloadPaths(text) {
30
+ const lines = text.split(/\r?\n/);
31
+ const pattern = lines.some((line) => /^\s*\*\*\*\s+Edit\s+File:/.test(line))
32
+ ? SLOPPY_TARGET
33
+ : lines.some((line) => /^\s*\*\*\*\s+(?:Add|Update|Delete)\s+File:/.test(line))
34
+ ? APPLY_PATCH_TARGET
35
+ : HASHLINE_TARGET;
36
+ const paths = [];
37
+ for (const line of lines) {
38
+ const match = pattern.exec(line);
39
+ const target = match && (match[1] ?? match[2] ?? match[3]);
40
+ if (target) paths.push(unquote(target.trim()));
41
+ }
42
+ return paths.length ? paths : [''];
43
+ }
44
+
45
+ function jsonObject(text) {
46
+ try {
47
+ const value = JSON.parse(text);
48
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
49
+ } catch {
50
+ return {};
51
+ }
52
+ }
53
+
54
+ function targetPath(input) {
55
+ return input.path || input.filePath || input.file_path || input.file || '';
56
+ }
57
+
58
+ /**
59
+ * Paths a tool call would mutate; null when the tool does not write files.
60
+ */
61
+ function mutationPaths(toolName, input) {
62
+ const args = input && typeof input === 'object' ? input : {};
63
+ if (toolName === 'write') {
64
+ const target = targetPath(args);
65
+ const device = typeof target === 'string' ? XD_DEVICE.exec(target) : null;
66
+ return device ? mutationPaths(device[1], jsonObject(args.content)) : [target];
67
+ }
68
+ if (toolName === 'edit' || toolName === 'apply_patch') {
69
+ // OMP also derives `path`/`paths` from hashline headers; the payload stays authoritative.
70
+ const payload = typeof args.input === 'string' ? args.input : args._input;
71
+ const paths = typeof payload === 'string' ? editPayloadPaths(payload) : [targetPath(args)];
72
+ if (Array.isArray(args.paths)) paths.push(...args.paths.filter((target) => typeof target === 'string'));
73
+ if (Array.isArray(args.edits)) {
74
+ for (const edit of args.edits) if (typeof edit?.rename === 'string' && edit.rename) paths.push(edit.rename);
75
+ }
76
+ return paths;
77
+ }
78
+ if (['ast_edit', 'ast-edit'].includes(toolName)) return Array.isArray(args.paths) && args.paths.length ? args.paths : [args.path || ''];
79
+ if (toolName === 'lsp' && (['rename', 'rename_file'].includes(args.action) || (args.action === 'code_actions' && args.apply === true))) {
80
+ const paths = [args.file || args.path || '', args.new_name || args.newName || ''];
81
+ if (args.action === 'code_actions' && Array.isArray(args.edits)) {
82
+ for (const edit of args.edits) paths.push(edit?.file || edit?.path || '');
19
83
  }
20
84
  return paths.filter(Boolean).length ? paths.filter(Boolean) : [''];
21
85
  }
22
86
  return null;
23
87
  }
24
88
 
89
+ function nativeMutationPaths(event) {
90
+ return mutationPaths(event?.toolName, event?.input);
91
+ }
92
+
93
+ function expandHome(filePath) {
94
+ return filePath === '~' || filePath.startsWith('~/') ? path.join(os.homedir(), filePath.slice(1)) : filePath;
95
+ }
96
+
97
+ function isWithin(root, target) {
98
+ const relative = path.relative(root, target);
99
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
100
+ }
101
+
102
+ // Realpath of the deepest existing ancestor, with the missing tail re-attached.
103
+ function realTarget(target) {
104
+ const missing = [];
105
+ let current = target;
106
+ for (;;) {
107
+ try {
108
+ return path.join(fs.realpathSync(current), ...missing);
109
+ } catch {
110
+ const parent = path.dirname(current);
111
+ if (parent === current) return target;
112
+ missing.unshift(path.basename(current));
113
+ current = parent;
114
+ }
115
+ }
116
+ }
117
+
118
+ // The enclosing Git checkout; the project directory when it is not in one.
119
+ function checkoutRoot(cwd) {
120
+ const projectRoot = path.resolve(cwd);
121
+ for (let current = projectRoot; ; current = path.dirname(current)) {
122
+ if (fs.existsSync(path.join(current, '.git'))) return current;
123
+ if (path.dirname(current) === current) return projectRoot;
124
+ }
125
+ }
126
+
25
127
  function hasSymlinkComponent(cwd, target) {
26
128
  const projectRoot = path.resolve(cwd);
27
129
  const relative = path.relative(projectRoot, target);
@@ -48,6 +150,21 @@ function isPlanningPath(filePath, cwd) {
48
150
  return inside && !hasSymlinkComponent(cwd, resolved);
49
151
  }
50
152
 
153
+ /**
154
+ * True for a file in the parent checkout outside the planning directory. Unknown targets and
155
+ * unrecognized URL schemes count as checkout files, so the guard fails closed.
156
+ */
157
+ function isParentCheckoutSource(filePath, cwd) {
158
+ if (typeof filePath !== 'string' || !filePath.trim()) return true;
159
+ if (NON_CHECKOUT_URL.test(filePath)) return false;
160
+ if (URL_SCHEME.test(filePath)) return true;
161
+ const resolved = path.resolve(cwd, expandHome(filePath));
162
+ const root = checkoutRoot(cwd);
163
+ // A path outside the checkout can still reach into it through a symlink.
164
+ const inCheckout = isWithin(root, resolved) || isWithin(realTarget(root), realTarget(resolved));
165
+ return inCheckout && !isPlanningPath(resolved, cwd);
166
+ }
167
+
51
168
  /**
52
169
  * Native phase execution guard bound to the shared runtime state.
53
170
  */
@@ -57,8 +174,8 @@ function createPhaseGuard({ state, nativeTaskActivityCount }) {
57
174
  function nativePhaseWriteBlock(event, cwd) {
58
175
  const execution = nativePhaseExecutions.get(path.resolve(cwd));
59
176
  if (!execution || execution.interactive) return null;
60
- const mutationPaths = nativeMutationPaths(event);
61
- if (!mutationPaths || mutationPaths.every((filePath) => isPlanningPath(filePath, cwd))) return null;
177
+ const paths = nativeMutationPaths(event);
178
+ if (!paths || !paths.some((filePath) => isParentCheckoutSource(filePath, cwd))) return null;
62
179
  return 'GSD OMP guard: native phase execution must dispatch an isolated gsd-executor task for repository file changes; do not edit source files in the parent checkout.';
63
180
  }
64
181
 
@@ -70,9 +187,27 @@ function createPhaseGuard({ state, nativeTaskActivityCount }) {
70
187
  nativePhaseExecutions.delete(projectPath);
71
188
  }
72
189
 
190
+ function recordNativePhaseCheckpoint(cwd, output) {
191
+ const execution = nativePhaseExecutions.get(path.resolve(cwd));
192
+ if (!execution) return;
193
+ const statuses = [...String(output || '').matchAll(CHECKPOINT_STATUS)];
194
+ if (statuses.length) execution.lastCheckpointStatus = statuses.at(-1)[1].toLowerCase();
195
+ }
196
+
197
+ // STATE.md can say `executing` long after a run stopped, so an agent run that ends with no
198
+ // native task running releases the guard when it never dispatched or its last plan failed.
199
+ function releaseStoppedNativePhase(cwd) {
200
+ const projectPath = path.resolve(cwd);
201
+ const execution = nativePhaseExecutions.get(projectPath);
202
+ if (!execution || nativeTaskActivityCount(cwd) > 0) return;
203
+ if (!execution.dispatched || execution.lastCheckpointStatus === 'failed') nativePhaseExecutions.delete(projectPath);
204
+ }
205
+
73
206
  return {
74
207
  nativePhaseWriteBlock,
208
+ recordNativePhaseCheckpoint,
75
209
  releaseInactiveNativePhase,
210
+ releaseStoppedNativePhase,
76
211
  };
77
212
  }
78
213
 
@@ -12,6 +12,7 @@ const { localizedPlanProgress, planProgress } = require('./phases.cjs');
12
12
  const { checkpointRecoveryLines, readNextAction, resumableCheckpoint } = require('./planning-store.cjs');
13
13
  const { isGsdProject, stateSnapshot } = require('./planning.cjs');
14
14
  const { nativeTaskRecovery, nativeTaskRecoveryLines } = require('./task-results.cjs');
15
+ const { updateNoticeStatus } = require('./update-check.cjs');
15
16
 
16
17
  function contextUsageFor(ctx) {
17
18
  if (typeof ctx?.getContextUsage !== 'function') return null;
@@ -50,7 +51,7 @@ function widgetColor(code, text) {
50
51
  /**
51
52
  * Status surfaces bound to the shared runtime state, Goal Mode and native task tracking.
52
53
  */
53
- function createStatusSurface({ state, goalModeStateFor, nativeTaskActivityCount, nativeTaskExecutionSnapshot }) {
54
+ function createStatusSurface({ state, goalModeStateFor, nativeTaskActivityCount, nativeTaskExecutionSnapshot, updateNotice }) {
54
55
  const { nativeRuntimeSignals } = state;
55
56
 
56
57
  function setNativeRuntimeSignal(cwd, signal) {
@@ -279,6 +280,8 @@ function createStatusSurface({ state, goalModeStateFor, nativeTaskActivityCount,
279
280
  if (signal?.kind === 'compacting') statusParts.push(chinese ? '压缩中' : 'compacting');
280
281
  if (signal?.kind === 'retrying') statusParts.push(chinese ? `重试 ${signal.attempt}/${signal.maxAttempts}` : `retry ${signal.attempt}/${signal.maxAttempts}`);
281
282
  if (usage) statusParts.push(`${usage.percent}% ${chinese ? '上下文' : 'context'}`);
283
+ const pendingUpdate = updateNotice();
284
+ if (pendingUpdate) statusParts.push(updateNoticeStatus(pendingUpdate, chinese));
282
285
  const statusText = statusParts.join(' · ');
283
286
  if (typeof ctx.ui.setWidget === 'function') ctx.ui.setWidget('gsd', widgetLines(ctx.cwd, goalState), { placement: 'aboveEditor' });
284
287
  if (typeof ctx.ui.setStatus === 'function') {
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Whether OMP's native task tool offers `isolated` dispatch in the current session.
5
+ *
6
+ * The task tool advertises `isolated` only while `task.isolation.enabled` is true and plan
7
+ * mode is off, and it rebuilds its schema from live settings, so the schema is the answer.
8
+ */
9
+
10
+ const ISOLATION_SETTING = 'task.isolation.enabled';
11
+
12
+ function schemaDeclaresIsolated(schema, seen = new Set()) {
13
+ if (!schema || typeof schema !== 'object' || seen.has(schema)) return false;
14
+ seen.add(schema);
15
+ const properties = schema.properties;
16
+ if (properties && typeof properties === 'object' && Object.hasOwn(properties, 'isolated')) return true;
17
+ return Object.values(schema).some((value) => schemaDeclaresIsolated(value, seen));
18
+ }
19
+
20
+ /**
21
+ * @returns {boolean|null} whether the task tool accepts `isolated`; null when the host cannot tell
22
+ */
23
+ function taskIsolationOffered(pi) {
24
+ if (typeof pi.getAllTools !== 'function') return null;
25
+ try {
26
+ const tools = pi.getAllTools();
27
+ const task = Array.isArray(tools) ? tools.find((tool) => tool?.name === 'task') : undefined;
28
+ if (!task) return null;
29
+ // OMP 18 tool schemas are arktype types; older hosts expose JSON Schema objects.
30
+ const parameters = task.parameters;
31
+ const schema = typeof parameters?.toJsonSchema === 'function' ? parameters.toJsonSchema() : parameters;
32
+ return schema && typeof schema === 'object' ? schemaDeclaresIsolated(schema) : null;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function isolationSetting(pi, registry) {
39
+ const scope = pi.pi?.settings;
40
+ const setting = scope && typeof registry?.lookup === 'function' ? registry.lookup(ISOLATION_SETTING) : undefined;
41
+ return setting ? { setting, scope } : null;
42
+ }
43
+
44
+ /**
45
+ * Makes isolated task dispatch available when nothing configures it, through a session-only
46
+ * override; an explicit user, project, env or protocol-host value is respected.
47
+ *
48
+ * @returns {{ available: boolean, enabled?: boolean, reason?: 'disabled' | 'plan-mode' }}
49
+ */
50
+ function ensureTaskIsolation(pi, registry) {
51
+ const offered = taskIsolationOffered(pi);
52
+ if (offered !== false) return { available: true };
53
+ const handle = isolationSetting(pi, registry);
54
+ if (!handle) return { available: false, reason: 'disabled' };
55
+ const { setting, scope } = handle;
56
+ try {
57
+ if (setting.get(scope) === true) return { available: false, reason: 'plan-mode' };
58
+ if (setting.provenance(scope) !== 'default') return { available: false, reason: 'disabled' };
59
+ setting.override(scope, true);
60
+ if (taskIsolationOffered(pi) !== false) return { available: true, enabled: true };
61
+ setting.clearOverride(scope);
62
+ return { available: false, reason: 'plan-mode' };
63
+ } catch {
64
+ return { available: false, reason: 'disabled' };
65
+ }
66
+ }
67
+
68
+ function taskIsolationMessage(reason, chinese) {
69
+ if (reason === 'plan-mode') {
70
+ return chinese
71
+ ? '阶段执行需要 OMP 隔离任务,但计划模式会隐藏 `isolated` 选项。请退出计划模式后重新运行 /gsd-execute-phase,或使用 --interactive。'
72
+ : 'Phase execution needs isolated OMP tasks, and plan mode hides the task `isolated` option. Leave plan mode and run /gsd-execute-phase again, or use --interactive.';
73
+ }
74
+ return chinese
75
+ ? [
76
+ '阶段执行需要 OMP 任务隔离,但当前 `task.isolation.enabled` 已关闭。启用方式:',
77
+ '',
78
+ 'omp config set task.isolation.enabled true',
79
+ '',
80
+ '设置会实时生效;然后重新运行 /gsd-execute-phase,或使用 --interactive。',
81
+ ].join('\n')
82
+ : [
83
+ 'Phase execution needs OMP task isolation, and `task.isolation.enabled` is off. Enable it with:',
84
+ '',
85
+ 'omp config set task.isolation.enabled true',
86
+ '',
87
+ 'OMP reloads the setting live; then run /gsd-execute-phase again, or use --interactive.',
88
+ ].join('\n');
89
+ }
90
+
91
+ module.exports = {
92
+ ensureTaskIsolation,
93
+ taskIsolationMessage,
94
+ taskIsolationOffered,
95
+ };
@@ -0,0 +1,262 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Background "gsd-for-omp update available" check for GSD project sessions.
5
+ *
6
+ * Mirrors GSD Core's SessionStart update check: the registry lookup runs in the
7
+ * background, its result is cached for a day, and failures never surface. The
8
+ * extension shows at most one notification per instance plus a footer marker.
9
+ */
10
+
11
+ const fs = require('node:fs');
12
+ const os = require('node:os');
13
+ const path = require('node:path');
14
+ const { spawn } = require('node:child_process');
15
+ const packageJson = require('../../package.json');
16
+
17
+ const PACKAGE_NAME = packageJson.name;
18
+ const MANIFEST_NAME = '.gsd-for-omp-manifest.json';
19
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
20
+ const FAILED_CHECK_RETRY_MS = 60 * 60 * 1000;
21
+ const NPM_VIEW_TIMEOUT_MS = 15_000;
22
+ const MAX_NPM_OUTPUT = 64 * 1024;
23
+
24
+ function parseVersion(value) {
25
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(value ?? '').trim());
26
+ return match ? match.slice(1).map(Number) : null;
27
+ }
28
+
29
+ function isNewerVersion(candidate, current) {
30
+ const a = parseVersion(candidate);
31
+ const b = parseVersion(current);
32
+ if (!a || !b) return false;
33
+ for (let index = 0; index < 3; index += 1) {
34
+ if (a[index] !== b[index]) return a[index] > b[index];
35
+ }
36
+ return false;
37
+ }
38
+
39
+ function enabledFlag(value) {
40
+ return value !== undefined && value !== '' && !/^(0|false|no|off)$/i.test(String(value));
41
+ }
42
+
43
+ function updateCheckDisabled(env) {
44
+ return enabledFlag(env.GSD_FOR_OMP_NO_UPDATE_CHECK)
45
+ || enabledFlag(env.NO_UPDATE_NOTIFIER)
46
+ || enabledFlag(env.CI);
47
+ }
48
+
49
+ function defaultCacheFile(env) {
50
+ const cacheRoot = env.XDG_CACHE_HOME ? path.resolve(env.XDG_CACHE_HOME) : path.join(os.homedir(), '.cache');
51
+ return path.join(cacheRoot, PACKAGE_NAME, 'update-check.json');
52
+ }
53
+
54
+ /**
55
+ * Resolve the npm `latest` version through the user's npm configuration, the
56
+ * same lookup `gsd-for-omp update` performs. Bounded, abortable, never throws.
57
+ */
58
+ function npmLatestVersion({ signal, timeout = NPM_VIEW_TIMEOUT_MS, spawnChild = spawn } = {}) {
59
+ return new Promise((resolve) => {
60
+ let child;
61
+ let stdout = '';
62
+ let settled = false;
63
+ let timeoutTimer;
64
+ let killTimer;
65
+ const finish = (version = null) => {
66
+ if (settled) return;
67
+ settled = true;
68
+ clearTimeout(timeoutTimer);
69
+ clearTimeout(killTimer);
70
+ signal?.removeEventListener('abort', stop);
71
+ resolve(version);
72
+ };
73
+ function stop() {
74
+ try { child?.kill('SIGTERM'); } catch { /* already exited */ }
75
+ killTimer = setTimeout(() => {
76
+ try { child?.kill('SIGKILL'); } catch { /* already exited */ }
77
+ finish();
78
+ }, 250);
79
+ }
80
+ if (signal?.aborted) {
81
+ finish();
82
+ return;
83
+ }
84
+ try {
85
+ child = spawnChild('npm', ['view', PACKAGE_NAME, 'version', '--json'], {
86
+ stdio: ['ignore', 'pipe', 'ignore'],
87
+ windowsHide: true,
88
+ });
89
+ } catch {
90
+ finish();
91
+ return;
92
+ }
93
+ child.stdout.setEncoding('utf8');
94
+ child.stdout.on('data', (chunk) => {
95
+ if (stdout.length < MAX_NPM_OUTPUT) stdout += chunk;
96
+ });
97
+ child.on('error', () => finish());
98
+ child.on('close', (code) => {
99
+ if (code !== 0) return finish();
100
+ try {
101
+ const version = JSON.parse(stdout);
102
+ finish(typeof version === 'string' && parseVersion(version) ? version.trim() : null);
103
+ } catch {
104
+ finish();
105
+ }
106
+ });
107
+ signal?.addEventListener('abort', stop, { once: true });
108
+ timeoutTimer = setTimeout(stop, timeout);
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Per-instance update check. Every dependency is injectable so tests never
114
+ * touch the network or the user's cache directory.
115
+ */
116
+ function createUpdateCheck({
117
+ runtimeRoot,
118
+ env = process.env,
119
+ now = Date.now,
120
+ currentVersion = packageJson.version,
121
+ latestVersion = npmLatestVersion,
122
+ cacheFile,
123
+ } = {}) {
124
+ const cachePath = cacheFile || defaultCacheFile(env);
125
+ let latest = null;
126
+ let notice = null;
127
+ let notified = false;
128
+ let pending = null;
129
+ let controller = null;
130
+
131
+ function readCache() {
132
+ try {
133
+ const cached = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
134
+ if (!cached || typeof cached !== 'object' || !Number.isFinite(cached.checkedAt)) return null;
135
+ return {
136
+ checkedAt: cached.checkedAt,
137
+ latest: parseVersion(cached.latest) ? cached.latest : null,
138
+ ok: cached.ok === true,
139
+ };
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+
145
+ function writeCache(record) {
146
+ const temporary = `${cachePath}.${process.pid}.tmp`;
147
+ try {
148
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
149
+ fs.writeFileSync(temporary, `${JSON.stringify(record)}\n`);
150
+ fs.renameSync(temporary, cachePath);
151
+ } catch {
152
+ try { fs.rmSync(temporary, { force: true }); } catch { /* best effort */ }
153
+ }
154
+ }
155
+
156
+ function projectedVersion() {
157
+ try {
158
+ const version = JSON.parse(fs.readFileSync(path.join(runtimeRoot, MANIFEST_NAME), 'utf8'))?.version;
159
+ return typeof version === 'string' ? version : null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ function computeNotice() {
166
+ if (isNewerVersion(latest, currentVersion)) return { kind: 'available', latest, current: currentVersion, root: runtimeRoot };
167
+ const projected = projectedVersion();
168
+ if (projected && projected !== currentVersion) return { kind: 'reinstall', projected, current: currentVersion, root: runtimeRoot };
169
+ return null;
170
+ }
171
+
172
+ function announce(onNotice) {
173
+ notice = computeNotice();
174
+ if (!notice || notified) return;
175
+ notified = true;
176
+ try { onNotice(notice); } catch { /* advisory only */ }
177
+ }
178
+
179
+ /**
180
+ * Show what is already known (fresh or stale cache, projection drift) and
181
+ * refresh the registry result in the background when the cache is stale.
182
+ */
183
+ function startUpdateCheck(onNotice) {
184
+ if (updateCheckDisabled(env)) return;
185
+ const cached = readCache();
186
+ if (cached?.latest) latest = cached.latest;
187
+ const age = cached ? now() - cached.checkedAt : Infinity;
188
+ const fresh = age >= 0 && age < (cached?.ok ? CHECK_INTERVAL_MS : FAILED_CHECK_RETRY_MS);
189
+ if (fresh || pending) {
190
+ announce(onNotice);
191
+ return;
192
+ }
193
+ // A stale cached version is still a valid lower bound for "newer than installed".
194
+ if (isNewerVersion(latest, currentVersion)) announce(onNotice);
195
+ controller = new AbortController();
196
+ const { signal } = controller;
197
+ pending = Promise.resolve()
198
+ .then(() => latestVersion({ signal }))
199
+ .catch(() => null)
200
+ .then((version) => {
201
+ if (signal.aborted) return;
202
+ const resolved = parseVersion(version) ? String(version).trim() : null;
203
+ writeCache({ checkedAt: now(), latest: resolved || latest, ok: Boolean(resolved) });
204
+ if (resolved) latest = resolved;
205
+ announce(onNotice);
206
+ })
207
+ .finally(() => {
208
+ pending = null;
209
+ controller = null;
210
+ });
211
+ }
212
+
213
+ function cancelUpdateCheck() {
214
+ controller?.abort();
215
+ }
216
+
217
+ return {
218
+ cancelUpdateCheck,
219
+ startUpdateCheck,
220
+ updateNotice: () => notice,
221
+ _pendingUpdateCheck: () => pending,
222
+ };
223
+ }
224
+
225
+ function shellQuote(value) {
226
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
227
+ }
228
+
229
+ /**
230
+ * The suggested command always names the active runtime root: a terminal
231
+ * without this OMP session's PI_CODING_AGENT_DIR would otherwise target
232
+ * ~/.omp/agent and leave a custom-root projection stale.
233
+ */
234
+ function noticeCommand(notice, command) {
235
+ return `gsd-for-omp ${command} --root ${shellQuote(notice.root)}`;
236
+ }
237
+
238
+ function updateNoticeMessage(notice, chinese) {
239
+ if (notice.kind === 'available') {
240
+ const command = noticeCommand(notice, 'update');
241
+ return chinese
242
+ ? `gsd-for-omp ${notice.latest} 已发布(当前 ${notice.current})。请在终端运行 \`${command}\`,然后重启 OMP。`
243
+ : `gsd-for-omp ${notice.latest} is available (installed ${notice.current}). Run \`${command}\` in a terminal, then restart OMP.`;
244
+ }
245
+ const command = noticeCommand(notice, 'install');
246
+ return chinese
247
+ ? `已安装 gsd-for-omp ${notice.current},但 OMP 文件仍由 ${notice.projected} 生成。请在终端运行 \`${command}\`,然后重启 OMP。`
248
+ : `gsd-for-omp ${notice.current} is installed but the OMP files were generated by ${notice.projected}. Run \`${command}\` in a terminal, then restart OMP.`;
249
+ }
250
+
251
+ function updateNoticeStatus(notice, chinese) {
252
+ if (notice.kind === 'available') return chinese ? `⬆ 可更新 ${notice.latest}` : `⬆ ${notice.latest}`;
253
+ return chinese ? '⬆ 需重新安装' : '⬆ reinstall';
254
+ }
255
+
256
+ module.exports = {
257
+ createUpdateCheck,
258
+ npmLatestVersion,
259
+ updateCheckDisabled,
260
+ updateNoticeMessage,
261
+ updateNoticeStatus,
262
+ };
package/src/extension.cjs CHANGED
@@ -35,6 +35,7 @@ const { createSessionControls } = require('./extension/session-controls.cjs');
35
35
  const { createRuntimeState } = require('./extension/state.cjs');
36
36
  const { createStatusSurface } = require('./extension/status.cjs');
37
37
  const { createTaskResultsWriter } = require('./extension/task-results.cjs');
38
+ const { createUpdateCheck } = require('./extension/update-check.cjs');
38
39
 
39
40
  module.exports = function gsdPiExtension(pi, options = {}) {
40
41
  if (!pi || typeof pi !== 'object') {
@@ -56,7 +57,8 @@ module.exports = function gsdPiExtension(pi, options = {}) {
56
57
  const toolHooks = createToolHooks({ pi, state });
57
58
  const taskResults = createTaskResultsWriter();
58
59
  const { invokeAsync } = createCliBridge({ agentsDir, cliPath });
59
- const status = createStatusSurface({ state, ...goalMode, ...taskTracker });
60
+ const updateCheck = createUpdateCheck({ runtimeRoot, ...options.updateCheck });
61
+ const status = createStatusSurface({ state, ...goalMode, ...taskTracker, updateNotice: updateCheck.updateNotice });
60
62
  const nativeUi = createNativeUi({ pi, ...status });
61
63
  const sessionControls = createSessionControls({ pi, ...goalMode, ...taskTracker, ...status });
62
64
  const onboarding = createOnboarding({ state, ...status });
@@ -92,6 +94,7 @@ module.exports = function gsdPiExtension(pi, options = {}) {
92
94
  ...nativeUi,
93
95
  ...onboarding,
94
96
  ...continuation,
97
+ ...updateCheck,
95
98
  });
96
99
 
97
100
  gsdPiExtension._internals = {
@@ -100,6 +103,7 @@ module.exports = function gsdPiExtension(pi, options = {}) {
100
103
  widgetLines: status.widgetLines,
101
104
  _nativeTaskActivityCount: taskTracker.nativeTaskActivityCount,
102
105
  _nativeTaskExecutionSnapshot: taskTracker.nativeTaskExecutionSnapshot,
106
+ _pendingUpdateCheck: updateCheck._pendingUpdateCheck,
103
107
  };
104
108
  };
105
109
 
@@ -24,6 +24,16 @@ End the final report with exactly one lifecycle line, then follow OMP's terminal
24
24
  \`\`\`
25
25
 
26
26
  Use \`failed\` or \`cancelled\` instead of \`completed\` when the plan did not complete.
27
+
28
+ ## OMP isolated workspace branch
29
+
30
+ An OMP isolated task workspace is a private copy of the repository whose HEAD starts detached at the parent's commit, so the task commit protocol's HEAD safety assertion refuses to commit there. Before your first task commit, if \`git symbolic-ref --quiet HEAD\` fails, create a per-agent branch at that commit and keep committing on it:
31
+
32
+ \`\`\`bash
33
+ git switch -c "agent-phase{PHASE}-plan{PLAN}"
34
+ \`\`\`
35
+
36
+ The branch exists only inside the isolated workspace, and OMP captures your commits from HEAD whatever the branch is called (as a patch, or replayed onto \`omp/task/<id>\` in branch mode). If HEAD is already on a branch, leave it there.
27
37
  `;
28
38
 
29
39
  const EXECUTE_PHASE_SKILL = 'gsd-execute-phase';