@zq-silk/yui 0.13.5 → 0.13.7

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/ARCHITECTURE.md CHANGED
@@ -254,21 +254,20 @@ Yui's current attachment, not exclusive ownership of the Provider thread. One
254
254
  Turn identifies one provider-native execution. Yui's authority epoch fences
255
255
  only Yui's own submissions and retries.
256
256
 
257
- Codex Task threads can be opened and used directly in Desktop as ordinary
258
- sessions; no Yui takeover is required. If a direct user Turn is active, Yui
259
- keeps its pending Run/message and retries after that Turn settles. The explicit
260
- tmux takeover gateway remains for providers whose managed conversation is
261
- attached to an independent process. Global interactive entry remains a native
257
+ Codex Task threads remain ordinary native sessions and can be opened and used
258
+ directly in Desktop. If a direct user Turn is active, Yui keeps its pending
259
+ Run/message until that Turn settles. Global interactive entry remains a native
262
260
  session-lifecycle operation outside the Task delivery contract.
263
261
 
264
- Codex uses `app-server proxy` to create or resume a normal thread on the shared
265
- App Server daemon. Role model, effort, permission, workspace, and shell settings are passed at
262
+ Codex establishes an App Server WebSocket through the byte-forwarding
263
+ `app-server proxy` to create or resume a normal thread on the shared daemon.
264
+ Role model, effort, permission, workspace, and shell settings are passed at
266
265
  `thread/start`/`thread/resume`, while the ordinary Task message points to the
267
266
  Session Manifest and matching Role Skill. Yui does not write either to global
268
- Codex config and may only ensure that the daemon is running; it never restarts
269
- or stops it for a thread error. A Codex native config profile is rejected for
270
- Managed Codex because the protocol cannot isolate it to one thread; a Yui Agent
271
- Profile supplies the per-Role behavior, Skills, model, and effort instead.
267
+ Codex config. A native Codex profile is rejected because it cannot be isolated
268
+ to one shared-daemon thread. The Agent Host owns only its proxy and WebSocket:
269
+ Task execution stop discards the Yui attachment without waiting for or changing
270
+ the daemon or native thread, and start creates a new attachment.
272
271
  Claude uses a persistent stream-json
273
272
  transport with exact user-message replay acknowledgement. In both cases, Yui
274
273
  records Turn intent before writing, accepts only exact Provider evidence, and
package/README.md CHANGED
@@ -875,13 +875,14 @@ Provider conversations remain ordinary user conversations. Yui adds the Role
875
875
  Skill and Session Manifest pointer, then sends Task work through provider-native
876
876
  structured requests. Managed prompts are never delivered as terminal bytes.
877
877
 
878
- Codex uses `app-server proxy` to create or resume a normal thread on the shared
879
- App Server daemon. The thread is visible and directly usable in Desktop; Yui
880
- does not require takeover or install global Hook/config state. It may
881
- idempotently start an absent daemon, but never restarts or stops it for a thread
882
- error. When a user Turn is active, Yui keeps pending Task work and retries
883
- later. If Yui's proxy disconnects, the Host reattaches without ending the
884
- logical Activation and reconciles the exact owned Turn from native history.
878
+ Codex establishes the App Server WebSocket protocol through `app-server proxy`
879
+ to create or resume an ordinary thread on the shared native daemon. The thread
880
+ remains visible and directly usable in Desktop. Task execution stop terminates
881
+ Yui's Agent Host and proxy while leaving the daemon and thread untouched; start
882
+ creates a fresh proxy attachment.
883
+ If the proxy disconnects, the Host may attach a bounded replacement client and
884
+ reconcile the exact owned Turn from native history. A failed fresh attachment
885
+ is released instead of becoming a cleanup prerequisite for later Runs.
885
886
  Claude Code keeps its independent stream-json process with exact
886
887
  user-message replay acknowledgement. A timeout or uncertain write becomes
887
888
  `delivery-unknown` and is never automatically retried.
@@ -894,10 +895,10 @@ yui task role takeover <task-id> <role>
894
895
  yui task role release <task-id> <role>
895
896
  ```
896
897
 
897
- For Codex, open the Role's ordinary thread in Desktop for direct interaction;
898
- these commands are not required. `view`/`takeover`/`release` remain the explicit
899
- PTY gateway for providers whose managed conversation uses an independent
900
- process.
898
+ For an independently hosted Provider such as Claude, these commands are the
899
+ supported human-control boundary. A Codex Role uses an ordinary shared thread
900
+ and may be operated directly in Desktop; an active Desktop Turn creates bounded
901
+ backpressure for Yui rather than a failed Run.
901
902
 
902
903
  Global Operator and global Role sessions remain native interactive CLIs:
903
904
 
@@ -962,7 +963,7 @@ movement cannot conceal a workflow that is not advancing.
962
963
 
963
964
  Stable Role context never creates a separate bootstrap Turn. Task execution Runs use the generic Leader or Worker Skill, while review Runs use the generic Reviewer Skill based on durable Run purpose rather than a configured Role name. The provider either carries the Skill through a safe additive native context channel or points to it from the ordinary Task delivery. These Yui-owned Role Skills define portable orchestration only. Project Skills remain ordinary versioned files in the Project and are discovered, selected, and loaded by the Agent through its native project mechanism; Yui does not scan, parse, copy, or inject them.
964
965
 
965
- Managed Codex keeps the user's native developer instructions unchanged. The ordinary Task message includes a compact absolute Session Manifest pointer, and the manifest identifies the matching Yui-owned Role Skill for Codex to read on demand. Model, effort, permission, workspace, and shell settings selected for the Role are supplied as thread-scoped `thread/start` or `thread/resume` configuration through the shared App Server daemon. A Codex native config profile cannot be isolated to one shared-daemon thread, so Managed Codex rejects that setting and directs callers to a Yui Agent Profile; ordinary non-Yui and interactive Codex sessions remain unaffected. Unrelated Codex threads keep their existing user, profile, project, and system configuration and the underlying config file is never mutated. App Server notifications are the managed thread's lifecycle authority; Yui installs no managed Codex Hook and does not claim `notify`. Interactive Codex Sessions may still use Yui's structured `notify` callback, and Doctor reports any effective configuration conflict. `skills.config` is not misused because it only enables or disables already-discovered Skills. Claude receives the same Yui-owned Role Skill content from a private `0600` managed context file rather than a large or sensitive argv value; retries and resumes reuse the purpose-specific Role path. Non-Operator global Roles stay neutral and receive no Task orchestration Skill. Operator therefore opens at an empty native composer, so the user's text remains its first user message. Leader wakeups and Worker or Reviewer Run assignments remain real mailbox-delivered work messages.
966
+ Managed Codex keeps the user's native developer instructions unchanged. The ordinary Task message includes a compact absolute Session Manifest pointer, and the manifest identifies the matching Yui-owned Role Skill for Codex to read on demand. Model, effort, permission, workspace, and shell settings are supplied to `thread/start` or `thread/resume` through the shared App Server daemon; a Codex native config profile is rejected because it cannot be isolated to one shared-daemon thread. The underlying Codex config file is never mutated. App Server notifications are the managed thread's lifecycle authority; Yui installs no managed Codex Hook and does not claim `notify`. Interactive Codex Sessions may still use Yui's structured `notify` callback, and Doctor reports any effective configuration conflict. `skills.config` is not misused because it only enables or disables already-discovered Skills. Claude receives the same Yui-owned Role Skill content from a private `0600` managed context file rather than a large or sensitive argv value; retries and resumes reuse the purpose-specific Role path. Non-Operator global Roles stay neutral and receive no Task orchestration Skill. Operator therefore opens at an empty native composer, so the user's text remains its first user message. Leader wakeups and Worker or Reviewer Run assignments remain real mailbox-delivered work messages.
966
967
 
967
968
  ## Controller and failure handling
968
969
 
@@ -172,8 +172,7 @@ class CodexAdapter extends BaseAdapter {
172
172
  ...launch,
173
173
  argv: [...argv, "app-server", "proxy"],
174
174
  transport: "codex-app-server-proxy",
175
- codexThread: codexThreadOptions(input, config),
176
- codexDaemonStartArgs: [...input.agent.baseArgs, "app-server", "daemon", "start"]
175
+ codexThread: codexThreadOptions(input, config)
177
176
  };
178
177
  }
179
178
  }
@@ -420,8 +420,9 @@ export class FileRoleLaunchPlanner {
420
420
  if (owner.scope !== "task" || input.runId === undefined) {
421
421
  args = addCodexSessionNotify(args, launchMode, this.#cliPath);
422
422
  }
423
- // Managed Codex Runs are ordinary shared-daemon threads. Their Session
424
- // Manifest points at the Yui Skills; no Yui Hook config is installed.
423
+ // Managed Codex Runs use disposable proxy clients against the shared
424
+ // native App Server. Their Session Manifest points at the Yui Skills;
425
+ // no Yui Hook config is installed.
425
426
  if (owner.scope === "task" && input.runId !== undefined) {
426
427
  if (managedRun === null || managedRun.status !== "active") {
427
428
  throw new Error(`Managed Codex Run is no longer active: ${input.runId}.`);
@@ -516,9 +517,6 @@ export class FileRoleLaunchPlanner {
516
517
  ...(managedCompiled.codexThread === undefined
517
518
  ? {}
518
519
  : { codexThread: managedCompiled.codexThread }),
519
- ...(managedCompiled.codexDaemonStartArgs === undefined
520
- ? {}
521
- : { codexDaemonStartArgs: managedCompiled.codexDaemonStartArgs }),
522
520
  ...(providerOwnedTurn === undefined ? {} : { ownedTurn: providerOwnedTurn }),
523
521
  authority: providerAuthority
524
522
  }
@@ -536,9 +534,6 @@ export class FileRoleLaunchPlanner {
536
534
  ...(managedCompiled.codexThread === undefined
537
535
  ? {}
538
536
  : { codexThread: managedCompiled.codexThread }),
539
- ...(managedCompiled.codexDaemonStartArgs === undefined
540
- ? {}
541
- : { codexDaemonStartArgs: managedCompiled.codexDaemonStartArgs }),
542
537
  authority: providerAuthority,
543
538
  initialTurn
544
539
  }
@@ -553,9 +548,6 @@ export class FileRoleLaunchPlanner {
553
548
  ...(managedCompiled.codexThread === undefined
554
549
  ? {}
555
550
  : { codexThread: managedCompiled.codexThread }),
556
- ...(managedCompiled.codexDaemonStartArgs === undefined
557
- ? {}
558
- : { codexDaemonStartArgs: managedCompiled.codexDaemonStartArgs }),
559
551
  authority: providerAuthority,
560
552
  initialTurn
561
553
  };
@@ -153,7 +153,6 @@ export async function runAgentHost(input) {
153
153
  ? {}
154
154
  : { sessionTitle: previousControl.sessionTitle }),
155
155
  codexThread: previousControl.codexThread,
156
- codexDaemonStartArgs: previousControl.codexDaemonStartArgs,
157
156
  ...(ownedTurn === undefined ? {} : { ownedTurn }),
158
157
  authority
159
158
  }
@@ -258,7 +257,7 @@ export async function runAgentHost(input) {
258
257
  ...(activeTurnAttemptId === undefined ? {} : { attemptId: activeTurnAttemptId }),
259
258
  ...(activeNativeTurnId === undefined ? {} : { nativeTurnId: activeNativeTurnId }),
260
259
  ...exitAuthority,
261
- detail: "Codex client disconnected; reattaching to the shared daemon."
260
+ detail: "Codex App Server proxy disconnected; attaching a replacement client."
262
261
  }));
263
262
  await reconnectCodexClient(providerSession, currentPayload);
264
263
  return;
@@ -121,7 +121,8 @@ export const BUILTIN_AGENT_DRIVERS = Object.freeze([
121
121
  }),
122
122
  observation: Object.freeze({
123
123
  ...STRUCTURED_CLI_CAPABILITIES.observation,
124
- // Managed Codex uses the ordinary shared App Server event stream.
124
+ // Managed Codex uses its Yui-owned proxy subscription to the shared
125
+ // App Server event stream.
125
126
  // Turn lifecycle is exact; Yui does not install per-thread Hooks merely
126
127
  // to manufacture tool/wait/usage observations.
127
128
  operations: Object.freeze([]),
@@ -93,18 +93,8 @@ function validateProviderControl(control) {
93
93
  if ((control.adapterId === "codex") !== (control.codexThread !== undefined)) {
94
94
  throw new Error("Agent Host Provider thread settings do not match its adapter.");
95
95
  }
96
- if ((control.adapterId === "codex") !== (control.codexDaemonStartArgs !== undefined)) {
97
- throw new Error("Agent Host Provider daemon bootstrap does not match its adapter.");
98
- }
99
96
  if (control.codexThread !== undefined)
100
97
  validateCodexThreadOptions(control.codexThread);
101
- if (control.codexDaemonStartArgs !== undefined) {
102
- if (!Array.isArray(control.codexDaemonStartArgs)
103
- || control.codexDaemonStartArgs.length === 0) {
104
- throw new Error("Agent Host Codex daemon bootstrap args are invalid.");
105
- }
106
- control.codexDaemonStartArgs.forEach((value) => text(value, "Codex daemon argument"));
107
- }
108
98
  if (control.mode !== "new" && control.mode !== "resume") {
109
99
  throw new Error("Agent Host Provider control mode is invalid.");
110
100
  }
@@ -1,11 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
+ import { Duplex } from "node:stream";
4
+ import WebSocket from "ws";
3
5
  import { CodexAppServerRequestError, CodexAppServerRuntime, codexAppServerErrorIsMissing } from "./codexAppServerRuntime.js";
4
6
  import { PROVIDER_ACCEPT_TIMEOUT_MS } from "./runtimeDeadlines.js";
5
7
  import { YUI_VERSION } from "../version.js";
6
8
  const PROVIDER_MESSAGE_MAX_BYTES = 16 * 1024 * 1024;
7
- const CODEX_DAEMON_START_TIMEOUT_MS = 10_000;
8
- const CODEX_DAEMON_OUTPUT_MAX_BYTES = 64 * 1024;
9
+ const CODEX_PROXY_HANDSHAKE_TIMEOUT_MS = 10_000;
9
10
  export class ProviderDeliveryUnknownError extends Error {
10
11
  attemptId;
11
12
  name = "ProviderDeliveryUnknownError";
@@ -46,9 +47,6 @@ export async function startStructuredProviderSession(payload, input = {}) {
46
47
  if (control === undefined) {
47
48
  throw new Error("Managed Agent Host launch requires Provider control metadata.");
48
49
  }
49
- if (control.adapterId === "codex") {
50
- await ensureCodexAppServerDaemon(payload, control);
51
- }
52
50
  const child = spawn(payload.command, [...payload.args], {
53
51
  cwd: payload.cwd,
54
52
  env: { ...payload.environment },
@@ -78,79 +76,57 @@ export async function startStructuredProviderSession(payload, input = {}) {
78
76
  throw error;
79
77
  }
80
78
  }
81
- async function ensureCodexAppServerDaemon(payload, control) {
82
- if (payload.args.at(-2) !== "app-server" || payload.args.at(-1) !== "proxy")
83
- return;
84
- if (control.adapterId !== "codex")
85
- return;
86
- const environment = Object.fromEntries(Object.entries(payload.environment).filter(([key]) => (!key.startsWith("YUI_")
87
- && key !== "CODEX_INTERNAL_ORIGINATOR_OVERRIDE"
88
- && !["TMPDIR", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR"]
89
- .includes(key))));
90
- const child = spawn(payload.command, [...control.codexDaemonStartArgs], {
91
- cwd: payload.cwd,
92
- env: environment,
93
- stdio: ["ignore", "pipe", "pipe"]
94
- });
95
- await new Promise((resolvePromise, reject) => {
96
- let output = "";
97
- let settled = false;
98
- let timer;
99
- const settle = (error) => {
100
- if (settled)
101
- return;
102
- settled = true;
103
- if (timer !== undefined)
104
- clearTimeout(timer);
105
- if (error === undefined)
106
- resolvePromise();
107
- else
108
- reject(error);
109
- };
110
- const capture = (chunk) => {
111
- output += String(chunk);
112
- if (Buffer.byteLength(output, "utf8") <= CODEX_DAEMON_OUTPUT_MAX_BYTES)
113
- return;
114
- child.kill("SIGTERM");
115
- settle(new Error("Codex App Server daemon start output exceeded its bound."));
116
- };
117
- child.stdout.on("data", capture);
118
- child.stderr.on("data", capture);
119
- child.once("error", (error) => settle(error));
120
- child.once("close", (code, signal) => {
121
- if (code === 0)
122
- settle();
123
- else
124
- settle(new Error(`Codex App Server daemon start failed (${code ?? signal ?? "unknown"})${output.trim().length === 0 ? "" : `: ${output.trim()}`}`));
125
- });
126
- timer = setTimeout(() => {
127
- child.kill("SIGTERM");
128
- settle(new Error("Codex App Server daemon start timed out."));
129
- }, CODEX_DAEMON_START_TIMEOUT_MS);
130
- timer.unref();
131
- });
132
- }
133
- class JsonLineChannel {
79
+ class CodexProxyWebSocketChannel {
134
80
  child;
135
81
  mirror;
136
82
  #pending = new Map();
137
83
  #listeners = new Set();
138
- #buffer = "";
139
84
  #nextId = 1;
140
85
  #closedError;
86
+ #ready = false;
87
+ #readyPromise;
88
+ #resolveReady;
89
+ #rejectReady;
90
+ #webSocket;
141
91
  constructor(child, mirror) {
142
92
  this.child = child;
143
93
  this.mirror = mirror;
144
- child.stdout.setEncoding("utf8");
145
- child.stdout.on("data", (chunk) => this.#receive(chunk));
94
+ let resolveReady;
95
+ let rejectReady;
96
+ this.#readyPromise = new Promise((resolvePromise, reject) => {
97
+ resolveReady = resolvePromise;
98
+ rejectReady = reject;
99
+ });
100
+ this.#resolveReady = resolveReady;
101
+ this.#rejectReady = rejectReady;
102
+ const transport = new ChildProcessDuplex(child);
103
+ this.#webSocket = new WebSocket("ws://localhost/rpc", {
104
+ createConnection: () => transport,
105
+ handshakeTimeout: CODEX_PROXY_HANDSHAKE_TIMEOUT_MS,
106
+ maxPayload: PROVIDER_MESSAGE_MAX_BYTES,
107
+ perMessageDeflate: false
108
+ });
109
+ this.#webSocket.once("open", () => {
110
+ this.#ready = true;
111
+ this.#resolveReady();
112
+ });
113
+ this.#webSocket.on("message", (data, isBinary) => this.#receive(data, isBinary));
114
+ this.#webSocket.on("error", (error) => this.#close(error));
115
+ this.#webSocket.once("close", (code, reason) => this.#close(new Error(`Codex App Server proxy WebSocket closed (code=${code}, reason=${reason.toString() || "none"}).`)));
146
116
  child.once("error", (error) => this.#close(error));
147
117
  child.once("close", (code, signal) => this.#close(new Error(`Provider process exited before replying (code=${code ?? "none"}, signal=${signal ?? "none"}).`)));
148
118
  }
119
+ static async connect(child, mirror) {
120
+ const channel = new CodexProxyWebSocketChannel(child, mirror);
121
+ await channel.#readyPromise;
122
+ return channel;
123
+ }
149
124
  onMessage(listener) {
150
125
  this.#listeners.add(listener);
151
126
  return () => this.#listeners.delete(listener);
152
127
  }
153
128
  async request(method, params) {
129
+ await this.#readyPromise;
154
130
  if (this.#closedError !== undefined)
155
131
  throw this.#closedError;
156
132
  const id = String(this.#nextId++);
@@ -177,6 +153,136 @@ class JsonLineChannel {
177
153
  async notify(method, params) {
178
154
  await this.send({ method, ...(params === undefined ? {} : { params }) });
179
155
  }
156
+ async send(message) {
157
+ await this.#readyPromise;
158
+ if (this.#closedError !== undefined)
159
+ throw this.#closedError;
160
+ const encoded = JSON.stringify(message);
161
+ if (Buffer.byteLength(encoded, "utf8") > PROVIDER_MESSAGE_MAX_BYTES) {
162
+ throw new Error("Provider request exceeds its message bound.");
163
+ }
164
+ await new Promise((resolvePromise, reject) => {
165
+ this.#webSocket.send(encoded, (error) => {
166
+ if (error === undefined || error === null)
167
+ resolvePromise();
168
+ else
169
+ reject(error);
170
+ });
171
+ });
172
+ }
173
+ #receive(data, isBinary) {
174
+ const encoded = Buffer.isBuffer(data)
175
+ ? data
176
+ : data instanceof ArrayBuffer
177
+ ? Buffer.from(data)
178
+ : Buffer.concat(data);
179
+ if (isBinary || encoded.byteLength > PROVIDER_MESSAGE_MAX_BYTES) {
180
+ this.#close(new Error(isBinary
181
+ ? "Provider returned an unsupported binary WebSocket message."
182
+ : "Provider response message exceeds its bound."));
183
+ terminateProcessGroup(this.child, "SIGTERM");
184
+ return;
185
+ }
186
+ const text = encoded.toString("utf8");
187
+ this.mirror("stdout", `${text}\n`);
188
+ let message;
189
+ try {
190
+ const parsed = JSON.parse(text);
191
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
192
+ return;
193
+ message = parsed;
194
+ }
195
+ catch {
196
+ return;
197
+ }
198
+ const id = requestId(message.id);
199
+ const pending = id === undefined ? undefined : this.#pending.get(id);
200
+ if (pending !== undefined) {
201
+ clearTimeout(pending.timer);
202
+ this.#pending.delete(id);
203
+ const error = object(message.error);
204
+ if (error !== null) {
205
+ pending.reject(new CodexAppServerRequestError(typeof error.code === "number" || typeof error.code === "string"
206
+ ? error.code
207
+ : "UNKNOWN", typeof error.message === "string" ? error.message : "Provider request failed.", error.data));
208
+ }
209
+ else {
210
+ pending.resolve(object(message.result) ?? {});
211
+ }
212
+ return;
213
+ }
214
+ for (const listener of this.#listeners)
215
+ listener(message);
216
+ }
217
+ #close(error) {
218
+ if (this.#closedError !== undefined)
219
+ return;
220
+ this.#closedError = error;
221
+ if (!this.#ready)
222
+ this.#rejectReady(error);
223
+ for (const pending of this.#pending.values()) {
224
+ clearTimeout(pending.timer);
225
+ pending.reject(error);
226
+ }
227
+ this.#pending.clear();
228
+ if (this.child.exitCode === null && this.child.signalCode === null) {
229
+ terminateProcessGroup(this.child, "SIGTERM");
230
+ }
231
+ }
232
+ }
233
+ class ChildProcessDuplex extends Duplex {
234
+ child;
235
+ connecting = false;
236
+ constructor(child) {
237
+ super();
238
+ this.child = child;
239
+ child.stdout.on("data", (chunk) => {
240
+ if (!this.push(chunk))
241
+ child.stdout.pause();
242
+ });
243
+ child.stdout.once("end", () => this.push(null));
244
+ child.once("error", (error) => this.destroy(error));
245
+ child.once("close", () => this.destroy());
246
+ }
247
+ _read() {
248
+ this.child.stdout.resume();
249
+ }
250
+ _write(chunk, encoding, callback) {
251
+ this.child.stdin.write(chunk, encoding, callback);
252
+ }
253
+ _final(callback) {
254
+ this.child.stdin.end(callback);
255
+ }
256
+ setNoDelay() {
257
+ return this;
258
+ }
259
+ setKeepAlive() {
260
+ return this;
261
+ }
262
+ setTimeout(_timeout, callback) {
263
+ if (callback !== undefined)
264
+ this.once("timeout", callback);
265
+ return this;
266
+ }
267
+ }
268
+ class JsonLineChannel {
269
+ child;
270
+ mirror;
271
+ #listeners = new Set();
272
+ #buffer = "";
273
+ #closedError;
274
+ constructor(child, mirror) {
275
+ this.child = child;
276
+ this.mirror = mirror;
277
+ child.stdout.setEncoding("utf8");
278
+ child.stdout.on("data", (chunk) => this.#receive(chunk));
279
+ child.once("error", (error) => this.#close(error));
280
+ child.once("close", (code, signal) => this.#close(new Error(`Provider process exited (code=${code ?? "none"}, signal=${signal ?? "none"}).`)));
281
+ }
282
+ onMessage(listener) {
283
+ this.#listeners.add(listener);
284
+ return () => this.#listeners.delete(listener);
285
+ }
180
286
  async send(message) {
181
287
  if (this.#closedError !== undefined)
182
288
  throw this.#closedError;
@@ -209,45 +315,21 @@ class JsonLineChannel {
209
315
  this.#buffer = this.#buffer.slice(newline + 1);
210
316
  if (line.length === 0)
211
317
  continue;
212
- let message;
213
318
  try {
214
319
  const parsed = JSON.parse(line);
215
320
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
216
321
  continue;
217
- message = parsed;
322
+ for (const listener of this.#listeners)
323
+ listener(parsed);
218
324
  }
219
325
  catch {
220
326
  continue;
221
327
  }
222
- const id = requestId(message.id);
223
- const pending = id === undefined ? undefined : this.#pending.get(id);
224
- if (pending !== undefined) {
225
- clearTimeout(pending.timer);
226
- this.#pending.delete(id);
227
- const error = object(message.error);
228
- if (error !== null) {
229
- pending.reject(new CodexAppServerRequestError(typeof error.code === "number" || typeof error.code === "string"
230
- ? error.code
231
- : "UNKNOWN", typeof error.message === "string" ? error.message : "Provider request failed.", error.data));
232
- }
233
- else {
234
- pending.resolve(object(message.result) ?? {});
235
- }
236
- continue;
237
- }
238
- for (const listener of this.#listeners)
239
- listener(message);
240
328
  }
241
329
  }
242
330
  #close(error) {
243
- if (this.#closedError !== undefined)
244
- return;
245
- this.#closedError = error;
246
- for (const pending of this.#pending.values()) {
247
- clearTimeout(pending.timer);
248
- pending.reject(error);
249
- }
250
- this.#pending.clear();
331
+ if (this.#closedError === undefined)
332
+ this.#closedError = error;
251
333
  }
252
334
  }
253
335
  class CodexStructuredProviderSession {
@@ -271,7 +353,7 @@ class CodexStructuredProviderSession {
271
353
  this.onTerminal = onTerminal;
272
354
  }
273
355
  static async open(child, exit, processInstanceId, payload, control, onTerminal, mirror) {
274
- const channel = new JsonLineChannel(child, mirror);
356
+ const channel = await CodexProxyWebSocketChannel.connect(child, mirror);
275
357
  const openingMessages = [];
276
358
  const stopOpeningBuffer = channel.onMessage((message) => openingMessages.push(message));
277
359
  await channel.request("initialize", {
@@ -347,7 +347,7 @@ export class TmuxSessionHost {
347
347
  : { [YUI_TASK_RUNTIME_DESCRIPTOR]: frozenTaskRuntime })
348
348
  }
349
349
  };
350
- let hostCreated;
350
+ let hostCreated = false;
351
351
  let providerAcknowledged = false;
352
352
  let providerDeliveryUnknown = false;
353
353
  let providerBusy = false;
@@ -420,6 +420,14 @@ export class TmuxSessionHost {
420
420
  }
421
421
  catch (error) {
422
422
  broker.revoke(request.launchId);
423
+ if (hostCreated && !providerDispatchObserved) {
424
+ try {
425
+ await stopExactRole(this.tmux, hostId, request.owner.roleName);
426
+ }
427
+ catch (stopError) {
428
+ throw new Error(`Managed Provider launch failed and its disposable Agent Host could not be stopped: ${stopError instanceof Error ? stopError.message : String(stopError)}`, { cause: stopError });
429
+ }
430
+ }
423
431
  throw error;
424
432
  }
425
433
  if (providerDispatchObserved
@@ -510,9 +510,9 @@ Task 生命周期的交互选择只展示有效来源状态:activate 只展示
510
510
 
511
511
  ## Session 与 tmux
512
512
 
513
- 受管理的 Provider 会话仍然是普通用户会话。Yui 只添加对应的 Role Skill 与 Session Manifest 指针,并通过 Provider 原生结构化协议提交 Task 工作;Yui 不接管完整对话历史。受管理输入绝不会作为终端按键、粘贴文本或启动 argv 发送。Codex 通过 `app-server proxy` 在共享 App Server daemon 上创建或恢复普通 thread;proxy 断开时 Host 会保留逻辑 Activation,重新连接并用原生 thread 历史核对 Yui 已持有的 Turn。Claude 继续使用独立的持久 stream-json 进程,并以精确回放的 user message 作为接收确认。
513
+ 受管理的 Provider 会话仍然是普通用户会话。Yui 只添加对应的 Role Skill 与 Session Manifest 指针,并通过 Provider 原生结构化协议提交 Task 工作;Yui 不接管完整对话历史。受管理输入绝不会作为终端按键、粘贴文本或启动 argv 发送。Codex 在只转发字节的 `app-server proxy` 上完成 App Server WebSocket 握手,接入与 Desktop 相同的共享 daemon;原生 thread 可在 Desktop 中直接查看和操作。Task execution stop 只终止 Yui Agent Host、WebSocket 与 proxy,保留共享 daemon、原生 thread、Task、WorkItem、代码与持久消息;start 创建新的 attachment。Claude 继续使用独立的持久 stream-json 进程,并以精确回放的 user message 作为接收确认。
514
514
 
515
- Run、Conversation、Activation 与 Turn 是四个独立身份。Conversation 可以跨多个 Run 和客户端连接;Activation 只代表 Yui 当前的连接,而不是对 Provider thread 的独占所有权;Turn 在写入前先持久化。写入超时或结果不明确会进入 `delivery-unknown`,不会自动重发。用户在 Desktop 直接发起的 active Turn 只会让 Yui 暂时等待,不会导致 Yui Run 失败。
515
+ Run、Conversation、Activation 与 Turn 是四个独立身份。Conversation 可以跨多个 Run 和客户端连接;Activation 只代表 Yui 当前的连接,而不是对 Provider thread 的独占所有权;Turn 在写入前先持久化。写入超时或结果不明确会进入 `delivery-unknown`,不会自动重发。Codex 已存在的原生 active Turn 只会让 Yui 暂时等待,不会导致 Yui Run 失败;Claude 等独立进程 Provider 继续通过 Yui 的 view/takeover 边界进行人工控制。
516
516
 
517
517
  Task Role 使用以下显式入口:
518
518
 
@@ -524,7 +524,7 @@ yui task role takeover <task-id> <role>
524
524
  yui task role release <task-id> <role>
525
525
  ```
526
526
 
527
- Codex Role thread 可以直接在 Desktop 中打开和交互,不需要执行 `takeover`;Yui 不写入全局 Hook/config。Yui 可以幂等启动尚未运行的共享 daemon,但不会因 thread 错误停止或重启它。`view`、`takeover`、`release` 继续作为独立进程型 Provider 的显式 PTY 输入网关。Global Operator 与 global Role 继续使用原生交互式 CLI,不属于受管理 Task Provider 协议。
527
+ Codex Role thread 可在 Desktop 中直接查看和操作;Desktop 已有 active Turn 时,Yui 只保留待投递工作并等待,不会失败或重复投递。`view`、`takeover`、`release` 继续作为 Claude 等独立进程 Provider 的人工控制入口。Yui 不写入全局 Hook/config,也不启动、重启或停止共享 daemon;Codex CLI/daemon 故障由 Task 生命周期之外修复。Global Operator 与 global Role 继续使用原生交互式 CLI,不属于受管理 Task Provider 协议。
528
528
 
529
529
  当新版本需要离线迁移 Home 时,应等待当前 Turn/Run 完成,然后从普通 shell
530
530
  执行 `yui session stop --all`,再重新执行 `yui update`。停止命令会先整体预检:
@@ -560,7 +560,7 @@ state、receipt 与 pane fence。Yui 不会解析 prompt glyph、进度文本、
560
560
  或其他 Agent 终端输出来推断 ready 或 success。`captureRole()` 只用于显式的人类
561
561
  transcript 查看,不具备生命周期权威。
562
562
 
563
- 稳定的 Role 上下文不会创建额外的 bootstrap Turn。Task execution Run 按角色使用通用 Leader 或 Worker Skill,review Run 则按持久 Run purpose 使用通用 Reviewer Skill;Provider 可以通过安全的追加式原生上下文通道携带 Skill,也可以在普通 Task 投递中指向它。这些都只是 Yui 自己拥有的可移植编排规则。Project Skills 始终是 Project 中正常版本化的文件,由 Agent 通过自身项目机制发现、选择并按需加载;Yui 不扫描、不解析、不复制,也不注入 Project Skills。Managed Codex 保留用户原有的 developer instructions;普通 Task 消息会携带精简的 Session Manifest 绝对路径,Manifest 再指向对应的 Yui Role Skill,供 Codex 按需读取。Role 选择的 model、effort、permission、workspace 与 shell 设置通过共享 App Server daemon,作为线程级 `thread/start` 或 `thread/resume` 配置传入。Codex 原生 config profile 不能隔离到共享 daemon 的单个 thread,因此 Managed Codex 会拒绝这个设置并提示使用 Yui Agent Profile;其他非 Yui 或交互式 Codex 会话不受影响。其他 Codex 线程继续使用原有的用户、profile、Project 和 system 配置,Yui 不修改底层配置文件。App Server 原生通知是 Managed Codex 线程的生命周期权威;Yui 不为它安装 Hook,也不占用 `notify`。交互式 Codex Session 仍可使用 Yui 的结构化 `notify` callback,Doctor 会报告最终生效的配置冲突。`skills.config` 只负责启停已发现 Skill,Yui 不会误用它。Claude 从 Yui 管理的私有 `0600` context 文件读取同一份 Yui Role Skill 内容,不再把大段或敏感文本放进 argv;重试和 resume 会复用按 purpose 区分的稳定路径。非 Operator 的 global Role 保持中性,不会注入 Task 编排 Skill。因此 Operator 会停在空白的原生 composer,用户输入仍是第一条 user message;Leader wake、Worker 和 Reviewer Run assignment 仍是邮箱投递的真实工作消息。
563
+ 稳定的 Role 上下文不会创建额外的 bootstrap Turn。Task execution Run 按角色使用通用 Leader 或 Worker Skill,review Run 则按持久 Run purpose 使用通用 Reviewer Skill;Provider 可以通过安全的追加式原生上下文通道携带 Skill,也可以在普通 Task 投递中指向它。这些都只是 Yui 自己拥有的可移植编排规则。Project Skills 始终是 Project 中正常版本化的文件,由 Agent 通过自身项目机制发现、选择并按需加载;Yui 不扫描、不解析、不复制,也不注入 Project Skills。Managed Codex 保留用户原有的 developer instructions;普通 Task 消息会携带精简的 Session Manifest 绝对路径,Manifest 再指向对应的 Yui Role Skill,供 Codex 按需读取。model、effort、permission、workspace 与 shell 设置作为共享 daemon 上的线程级 `thread/start` 或 `thread/resume` 配置传入;Codex 原生 config profile 因无法隔离到单条共享 thread 而被拒绝,Yui 不修改底层 Codex 配置文件。App Server 原生通知是 Managed Codex 线程的生命周期权威;Yui 不为它安装 Hook,也不占用 `notify`。交互式 Codex Session 仍可使用 Yui 的结构化 `notify` callback,Doctor 会报告最终生效的配置冲突。`skills.config` 只负责启停已发现 Skill,Yui 不会误用它。Claude 从 Yui 管理的私有 `0600` context 文件读取同一份 Yui Role Skill 内容,不再把大段或敏感文本放进 argv;重试和 resume 会复用按 purpose 区分的稳定路径。非 Operator 的 global Role 保持中性,不会注入 Task 编排 Skill。因此 Operator 会停在空白的原生 composer,用户输入仍是第一条 user message;Leader wake、Worker 和 Reviewer Run assignment 仍是邮箱投递的真实工作消息。
564
564
 
565
565
  ## Controller 与失败处理
566
566
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zq-silk/yui",
3
- "version": "0.13.5",
3
+ "version": "0.13.7",
4
4
  "description": "Local control plane for long-running native agent CLI sessions backed by tmux.",
5
5
  "license": "MIT",
6
6
  "private": false,