@aiwayds/dsh-opentui 0.21.1 → 0.23.0

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.
@@ -0,0 +1,2211 @@
1
+ // ../bridge/src/index.ts
2
+ import { randomUUID } from "node:crypto";
3
+ import { readFileSync as readFileSync2, realpathSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { dirname, join as join2 } from "node:path";
6
+
7
+ // ../bridge/src/ask-frames.ts
8
+ var ASK_FRAME_TYPES = {
9
+ REQUEST: "ask.request",
10
+ CANCEL: "ask.cancel",
11
+ PENDING: "ask.pending",
12
+ SETTLED: "ask.settled",
13
+ RESPONSE: "ask.response"
14
+ };
15
+ var ASK_ERROR_CODES = {
16
+ UNKNOWN_REQUEST: "ASK_UNKNOWN_REQUEST",
17
+ ALREADY_ANSWERED: "ASK_ALREADY_ANSWERED",
18
+ NOT_ADDRESSEE: "ASK_NOT_ADDRESSEE",
19
+ TURN_ENDED: "ASK_TURN_ENDED",
20
+ DEADLINE_EXCEEDED: "ASK_DEADLINE_EXCEEDED",
21
+ CHANNEL_UNAVAILABLE: "ASK_CHANNEL_UNAVAILABLE",
22
+ INVALID_RESPONSE: "ASK_INVALID_RESPONSE"
23
+ };
24
+ var ASK_ERROR_CODE_SET = new Set(Object.values(ASK_ERROR_CODES));
25
+ function isAskErrorCode(value) {
26
+ return typeof value === "string" && ASK_ERROR_CODE_SET.has(value);
27
+ }
28
+ function isRecord(value) {
29
+ return value !== null && typeof value === "object" && !Array.isArray(value);
30
+ }
31
+ function bad(code, message) {
32
+ return { ok: false, code, message };
33
+ }
34
+ function nonEmptyString(value, field, code) {
35
+ if (typeof value !== "string" || value === "")
36
+ return bad(code, `${field} must be a non-empty string`);
37
+ return value;
38
+ }
39
+ function optionalString(value, field, code) {
40
+ if (value === undefined)
41
+ return;
42
+ return nonEmptyString(value, field, code);
43
+ }
44
+ function optionalFiniteNumber(value, field, code) {
45
+ if (value === undefined)
46
+ return;
47
+ if (typeof value !== "number" || !Number.isFinite(value))
48
+ return bad(code, `${field} must be a finite number`);
49
+ return value;
50
+ }
51
+ function optionalBoolean(value, field, code) {
52
+ if (value === undefined)
53
+ return;
54
+ if (typeof value !== "boolean")
55
+ return bad(code, `${field} must be a boolean`);
56
+ return value;
57
+ }
58
+ function oneOf(value, allowed, field, code) {
59
+ if (typeof value !== "string" || !allowed.includes(value)) {
60
+ return bad(code, `${field} must be one of ${allowed.join("|")}`);
61
+ }
62
+ return value;
63
+ }
64
+ var KINDS = ["approval", "questions"];
65
+ var OUTCOMES = ["approved", "denied", "cancelled", "unavailable"];
66
+ var VERDICTS = ["allowed-once", "rejected", "unavailable"];
67
+ var BEHAVIORS = ["once", "always", "session"];
68
+ var CANCEL_REASONS = ["host-abort", "superseded", "deadline", "no-provider"];
69
+ function validateOption(value, code) {
70
+ if (!isRecord(value))
71
+ return bad(code, "question option must be an object");
72
+ const label = nonEmptyString(value.label, "option.label", code);
73
+ if (typeof label !== "string")
74
+ return label;
75
+ const description = optionalString(value.description, "option.description", code);
76
+ if (typeof description === "object")
77
+ return description;
78
+ return { ok: true, value: { label, ...description !== undefined ? { description } : {} } };
79
+ }
80
+ function validateQuestion(value, code) {
81
+ if (!isRecord(value))
82
+ return bad(code, "question must be an object");
83
+ const id = nonEmptyString(value.id, "question.id", code);
84
+ if (typeof id !== "string")
85
+ return id;
86
+ const prompt = nonEmptyString(value.prompt, "question.prompt", code);
87
+ if (typeof prompt !== "string")
88
+ return prompt;
89
+ if (!Array.isArray(value.options) || value.options.length === 0) {
90
+ return bad(code, "question.options must be a non-empty array");
91
+ }
92
+ const options = [];
93
+ for (const raw of value.options) {
94
+ const parsed = validateOption(raw, code);
95
+ if (!parsed.ok)
96
+ return parsed;
97
+ options.push(parsed.value);
98
+ }
99
+ const header = optionalString(value.header, "question.header", code);
100
+ if (typeof header === "object")
101
+ return header;
102
+ const description = optionalString(value.description, "question.description", code);
103
+ if (typeof description === "object")
104
+ return description;
105
+ const detail = optionalString(value.detail, "question.detail", code);
106
+ if (typeof detail === "object")
107
+ return detail;
108
+ const multiSelect = optionalBoolean(value.multiSelect, "question.multiSelect", code);
109
+ if (typeof multiSelect === "object")
110
+ return multiSelect;
111
+ return {
112
+ ok: true,
113
+ value: {
114
+ id,
115
+ prompt,
116
+ options,
117
+ ...header !== undefined ? { header } : {},
118
+ ...description !== undefined ? { description } : {},
119
+ ...detail !== undefined ? { detail } : {},
120
+ ...multiSelect !== undefined ? { multiSelect } : {}
121
+ }
122
+ };
123
+ }
124
+ function validateAnswer(value) {
125
+ const code = ASK_ERROR_CODES.INVALID_RESPONSE;
126
+ if (!isRecord(value))
127
+ return bad(code, "answer must be an object");
128
+ const id = nonEmptyString(value.id, "answer.id", code);
129
+ if (typeof id !== "string")
130
+ return id;
131
+ if (!Array.isArray(value.selected) || value.selected.some((s) => typeof s !== "string")) {
132
+ return bad(code, "answer.selected must be an array of strings");
133
+ }
134
+ const custom = optionalString(value.custom, "answer.custom", code);
135
+ if (typeof custom === "object")
136
+ return custom;
137
+ return { ok: true, value: { id, selected: value.selected, ...custom !== undefined ? { custom } : {} } };
138
+ }
139
+ function validateAskRequest(value) {
140
+ const code = "BAD_PARAMS";
141
+ if (!isRecord(value))
142
+ return bad(code, "ask.request payload must be an object");
143
+ const eventId = nonEmptyString(value.eventId, "eventId", code);
144
+ if (typeof eventId !== "string")
145
+ return eventId;
146
+ const sessionId = nonEmptyString(value.sessionId, "sessionId", code);
147
+ if (typeof sessionId !== "string")
148
+ return sessionId;
149
+ const kind = oneOf(value.kind, KINDS, "kind", code);
150
+ if (typeof kind !== "string")
151
+ return kind;
152
+ const toolName = optionalString(value.toolName, "toolName", code);
153
+ if (typeof toolName === "object")
154
+ return toolName;
155
+ const callId = optionalString(value.callId, "callId", code);
156
+ if (typeof callId === "object")
157
+ return callId;
158
+ const reason = optionalString(value.reason, "reason", code);
159
+ if (typeof reason === "object")
160
+ return reason;
161
+ const deadlineAt = optionalFiniteNumber(value.deadlineAt, "deadlineAt", code);
162
+ if (typeof deadlineAt === "object")
163
+ return deadlineAt;
164
+ const detachGraceMs = optionalFiniteNumber(value.detachGraceMs, "detachGraceMs", code);
165
+ if (typeof detachGraceMs === "object")
166
+ return detachGraceMs;
167
+ if (typeof detachGraceMs === "number" && detachGraceMs < 0)
168
+ return bad(code, "detachGraceMs must be >= 0");
169
+ const escalation = optionalBoolean(value.escalation, "escalation", code);
170
+ if (typeof escalation === "object")
171
+ return escalation;
172
+ let questions;
173
+ if (value.questions !== undefined) {
174
+ if (!Array.isArray(value.questions))
175
+ return bad(code, "questions must be an array");
176
+ questions = [];
177
+ for (const raw of value.questions) {
178
+ const parsed = validateQuestion(raw, code);
179
+ if (!parsed.ok)
180
+ return parsed;
181
+ questions.push(parsed.value);
182
+ }
183
+ }
184
+ return {
185
+ ok: true,
186
+ value: {
187
+ eventId,
188
+ sessionId,
189
+ kind,
190
+ ...toolName !== undefined ? { toolName } : {},
191
+ ...callId !== undefined ? { callId } : {},
192
+ ...reason !== undefined ? { reason } : {},
193
+ ...questions !== undefined ? { questions } : {},
194
+ ...deadlineAt !== undefined ? { deadlineAt } : {},
195
+ ...detachGraceMs !== undefined ? { detachGraceMs } : {},
196
+ ...escalation !== undefined ? { escalation } : {}
197
+ }
198
+ };
199
+ }
200
+ function validateAskCancel(value) {
201
+ const code = "BAD_PARAMS";
202
+ if (!isRecord(value))
203
+ return bad(code, "ask.cancel payload must be an object");
204
+ const eventId = nonEmptyString(value.eventId, "eventId", code);
205
+ if (typeof eventId !== "string")
206
+ return eventId;
207
+ const reason = oneOf(value.reason, CANCEL_REASONS, "reason", code);
208
+ if (typeof reason !== "string")
209
+ return reason;
210
+ return { ok: true, value: { eventId, reason } };
211
+ }
212
+ function validateAskPending(value) {
213
+ const code = "BAD_PARAMS";
214
+ if (!isRecord(value))
215
+ return bad(code, "ask.pending payload must be an object");
216
+ const sessionId = nonEmptyString(value.sessionId, "sessionId", code);
217
+ if (typeof sessionId !== "string")
218
+ return sessionId;
219
+ if (!Array.isArray(value.asks))
220
+ return bad(code, "asks must be an array");
221
+ const asks = [];
222
+ for (const raw of value.asks) {
223
+ const parsed = validateAskRequest(raw);
224
+ if (!parsed.ok)
225
+ return parsed;
226
+ asks.push(parsed.value);
227
+ }
228
+ return { ok: true, value: { sessionId, asks } };
229
+ }
230
+ function validateAskSettled(value) {
231
+ const code = "BAD_PARAMS";
232
+ if (!isRecord(value))
233
+ return bad(code, "ask.settled payload must be an object");
234
+ const eventId = nonEmptyString(value.eventId, "eventId", code);
235
+ if (typeof eventId !== "string")
236
+ return eventId;
237
+ const outcome = oneOf(value.outcome, OUTCOMES, "outcome", code);
238
+ if (typeof outcome !== "string")
239
+ return outcome;
240
+ return { ok: true, value: { eventId, outcome } };
241
+ }
242
+ function validateAskResponse(value) {
243
+ const code = ASK_ERROR_CODES.INVALID_RESPONSE;
244
+ if (!isRecord(value))
245
+ return bad(code, "ask.response params must be an object");
246
+ const eventId = nonEmptyString(value.eventId, "eventId", code);
247
+ if (typeof eventId !== "string")
248
+ return eventId;
249
+ const kind = oneOf(value.kind, KINDS, "kind", code);
250
+ if (typeof kind !== "string")
251
+ return kind;
252
+ let verdict;
253
+ if (value.verdict !== undefined) {
254
+ const parsed = oneOf(value.verdict, VERDICTS, "verdict", code);
255
+ if (typeof parsed !== "string")
256
+ return parsed;
257
+ verdict = parsed;
258
+ }
259
+ let answers;
260
+ if (value.answers !== undefined) {
261
+ if (!Array.isArray(value.answers))
262
+ return bad(code, "answers must be an array");
263
+ answers = [];
264
+ for (const raw of value.answers) {
265
+ const parsed = validateAnswer(raw);
266
+ if (!parsed.ok)
267
+ return parsed;
268
+ answers.push(parsed.value);
269
+ }
270
+ }
271
+ let behavior;
272
+ if (value.behavior !== undefined) {
273
+ const parsed = oneOf(value.behavior, BEHAVIORS, "behavior", code);
274
+ if (typeof parsed !== "string")
275
+ return parsed;
276
+ behavior = parsed;
277
+ }
278
+ const escalation = optionalBoolean(value.escalation, "escalation", code);
279
+ if (typeof escalation === "object")
280
+ return escalation;
281
+ if (behavior === "always" && escalation !== true) {
282
+ return bad(code, 'behavior:"always" requires escalation:true');
283
+ }
284
+ if (verdict === undefined && (answers === undefined || answers.length === 0)) {
285
+ return bad(code, "ask.response requires a verdict or a non-empty answers array");
286
+ }
287
+ return {
288
+ ok: true,
289
+ value: {
290
+ eventId,
291
+ kind,
292
+ ...verdict !== undefined ? { verdict } : {},
293
+ ...answers !== undefined ? { answers } : {},
294
+ ...behavior !== undefined ? { behavior } : {},
295
+ ...escalation !== undefined ? { escalation } : {}
296
+ }
297
+ };
298
+ }
299
+ function validateAskEvent(type, payload) {
300
+ switch (type) {
301
+ case ASK_FRAME_TYPES.REQUEST:
302
+ return validateAskRequest(payload);
303
+ case ASK_FRAME_TYPES.CANCEL:
304
+ return validateAskCancel(payload);
305
+ case ASK_FRAME_TYPES.PENDING:
306
+ return validateAskPending(payload);
307
+ case ASK_FRAME_TYPES.SETTLED:
308
+ return validateAskSettled(payload);
309
+ default:
310
+ return bad("BAD_PARAMS", `unsupported ask event type: ${type}`);
311
+ }
312
+ }
313
+
314
+ // ../bridge/src/ask-journal.ts
315
+ var ASK_JOURNAL_KINDS = {
316
+ REQUESTED: "ask.requested",
317
+ RESPONDED: "ask.responded",
318
+ CANCELLED: "ask.cancelled"
319
+ };
320
+ var ASK_PLUGIN_RECORD_PREFIX = "plugin:opentui/ask";
321
+ function askPluginRecordType(kind) {
322
+ return `${ASK_PLUGIN_RECORD_PREFIX}/${kind.slice("ask.".length)}`;
323
+ }
324
+ var ASK_GRANT_JOURNAL_TYPE = askPluginRecordType(ASK_JOURNAL_KINDS.RESPONDED);
325
+ var IDENTIFIER_CHARS = /[^A-Za-z0-9._:-]/g;
326
+ var MAX_IDENTIFIER_CHARS = 96;
327
+ function redactIdentifier(value, max = MAX_IDENTIFIER_CHARS) {
328
+ if (typeof value !== "string" || value === "")
329
+ return;
330
+ const cleaned = value.replace(IDENTIFIER_CHARS, "").slice(0, max);
331
+ return cleaned === "" ? undefined : cleaned;
332
+ }
333
+ function summarizeAnswers(answers) {
334
+ if (answers === undefined || answers.length === 0)
335
+ return;
336
+ return {
337
+ count: answers.length,
338
+ selections: answers.map((answer) => answer.selected.length)
339
+ };
340
+ }
341
+ function alwaysGrantToolsFromJournal(sessionId, rows) {
342
+ const expectedSession = redactIdentifier(sessionId) ?? sessionId;
343
+ const tools = new Set;
344
+ for (const row of rows) {
345
+ if (row.type !== ASK_GRANT_JOURNAL_TYPE)
346
+ continue;
347
+ const data = row.payload;
348
+ if (data === null || typeof data !== "object" || Array.isArray(data))
349
+ continue;
350
+ const event = data;
351
+ if (event.sessionId !== expectedSession)
352
+ continue;
353
+ if (event.behavior !== "always" || event.outcome !== "approved")
354
+ continue;
355
+ const tool = redactIdentifier(event.toolName);
356
+ if (tool !== undefined)
357
+ tools.add(tool);
358
+ }
359
+ return [...tools];
360
+ }
361
+
362
+ class SessionPermissionSummary {
363
+ #bySession = new Map;
364
+ has(sessionId, toolName) {
365
+ return this.#bySession.get(sessionId)?.has(toolName) === true;
366
+ }
367
+ grant(sessionId, toolName) {
368
+ let tools = this.#bySession.get(sessionId);
369
+ if (tools === undefined) {
370
+ tools = new Set;
371
+ this.#bySession.set(sessionId, tools);
372
+ }
373
+ tools.add(toolName);
374
+ }
375
+ restoreGrants(sessionId, tools) {
376
+ for (const tool of tools)
377
+ this.grant(sessionId, tool);
378
+ }
379
+ clearSession(sessionId) {
380
+ this.#bySession.delete(sessionId);
381
+ }
382
+ tools(sessionId) {
383
+ return [...this.#bySession.get(sessionId) ?? []];
384
+ }
385
+ count(sessionId) {
386
+ return this.#bySession.get(sessionId)?.size ?? 0;
387
+ }
388
+ clear() {
389
+ this.#bySession.clear();
390
+ }
391
+ }
392
+
393
+ // ../bridge/src/ask-registry.ts
394
+ var DEFAULT_RECORD_LIMIT = 256;
395
+ function remember(ids, id, limit) {
396
+ ids.add(id);
397
+ while (ids.size > limit) {
398
+ const oldest = ids.values().next().value;
399
+ if (oldest === undefined)
400
+ break;
401
+ ids.delete(oldest);
402
+ }
403
+ }
404
+ function turnIdOf(eventId) {
405
+ const i = eventId.lastIndexOf(":ask-");
406
+ return i === -1 ? eventId : eventId.slice(0, i);
407
+ }
408
+
409
+ class AskRegistry {
410
+ #askDeadlineMs;
411
+ #detachGraceMs;
412
+ #maxAskWaitMs;
413
+ #recordLimit;
414
+ #now;
415
+ #sink;
416
+ #journal;
417
+ #logger;
418
+ #pending = new Map;
419
+ #seqByTurn = new Map;
420
+ #settledIds = new Set;
421
+ #endedIds = new Set;
422
+ #settlementLog = [];
423
+ #summary = new SessionPermissionSummary;
424
+ #timers = new Set;
425
+ constructor(options = {}) {
426
+ this.#askDeadlineMs = options.askDeadlineMs === undefined ? null : options.askDeadlineMs;
427
+ this.#detachGraceMs = options.detachGraceMs ?? 30000;
428
+ this.#maxAskWaitMs = options.maxAskWaitMs ?? 3600000;
429
+ this.#recordLimit = options.recordLimit ?? DEFAULT_RECORD_LIMIT;
430
+ this.#now = options.now ?? Date.now;
431
+ this.#sink = options.sink ?? (() => {});
432
+ this.#journal = options.journal ?? (() => {});
433
+ this.#logger = options.logger;
434
+ }
435
+ timerCount() {
436
+ return this.#timers.size;
437
+ }
438
+ pendingCount() {
439
+ return this.#pending.size;
440
+ }
441
+ pendingIds() {
442
+ return [...this.#pending.keys()];
443
+ }
444
+ settlements() {
445
+ return this.#settlementLog;
446
+ }
447
+ sessionGrants(sessionId) {
448
+ return this.#summary.tools(sessionId);
449
+ }
450
+ hasGrant(sessionId, toolName) {
451
+ return this.#summary.has(sessionId, toolName);
452
+ }
453
+ clearSessionGrants(sessionId) {
454
+ this.#summary.clearSession(sessionId);
455
+ }
456
+ restoreSessionGrants(sessionId, tools) {
457
+ this.#summary.restoreGrants(sessionId, tools);
458
+ }
459
+ recordSummaryDecision(turnId, input) {
460
+ const eventId = this.nextEventId(turnId);
461
+ this.#writeJournal({
462
+ eventId,
463
+ kind: ASK_JOURNAL_KINDS.RESPONDED,
464
+ askKind: input.askKind,
465
+ sessionId: redactIdentifier(input.sessionId) ?? input.sessionId,
466
+ turnId: redactIdentifier(turnId) ?? turnId,
467
+ ...redactIdentifier(input.toolName) !== undefined ? { toolName: redactIdentifier(input.toolName) } : {},
468
+ verdict: "allowed-once",
469
+ outcome: "approved",
470
+ behavior: "always",
471
+ source: "summary",
472
+ at: this.#now()
473
+ });
474
+ return eventId;
475
+ }
476
+ #writeJournal(event) {
477
+ try {
478
+ this.#journal(event);
479
+ } catch (err) {
480
+ this.#logger?.warn?.("[ask-registry] journal sink threw (decision unchanged): %s", err);
481
+ }
482
+ }
483
+ nextEventId(turnId) {
484
+ const next = (this.#seqByTurn.get(turnId) ?? 0) + 1;
485
+ this.#seqByTurn.set(turnId, next);
486
+ return `${turnId}:ask-${next}`;
487
+ }
488
+ #arm(fn, delayMs) {
489
+ const handle = setTimeout(() => {
490
+ this.#timers.delete(handle);
491
+ fn();
492
+ }, Math.max(0, delayMs));
493
+ handle.unref?.();
494
+ this.#timers.add(handle);
495
+ return handle;
496
+ }
497
+ #disarm(handle) {
498
+ if (handle === undefined)
499
+ return;
500
+ clearTimeout(handle);
501
+ this.#timers.delete(handle);
502
+ }
503
+ #emit(frame) {
504
+ this.#sink(frame);
505
+ }
506
+ create(turnId, input) {
507
+ const eventId = this.nextEventId(turnId);
508
+ const request = { ...input, eventId };
509
+ const createdAt = this.#now();
510
+ const graceMs = input.detachGraceMs ?? this.#detachGraceMs;
511
+ const entry = { request, turnId, createdAt, deliveredTo: input.sessionId, graceMs };
512
+ this.#pending.set(eventId, entry);
513
+ const deadlineAt = request.deadlineAt ?? (this.#askDeadlineMs === null ? undefined : createdAt + this.#askDeadlineMs);
514
+ if (deadlineAt !== undefined) {
515
+ entry.deadlineTimer = this.#arm(() => {
516
+ this.#settle(entry, this.#deadlineOutcome(entry.request.kind), {
517
+ code: ASK_ERROR_CODES.DEADLINE_EXCEEDED,
518
+ cancelReason: "deadline",
519
+ message: "ask deadline exceeded",
520
+ source: "timeout"
521
+ });
522
+ }, deadlineAt - createdAt);
523
+ }
524
+ entry.hardCapTimer = this.#arm(() => {
525
+ this.#settle(entry, "unavailable", {
526
+ code: ASK_ERROR_CODES.DEADLINE_EXCEEDED,
527
+ cancelReason: "deadline",
528
+ message: "maxAskWaitMs hard cap exceeded",
529
+ source: "timeout"
530
+ });
531
+ }, this.#maxAskWaitMs);
532
+ this.#writeJournal({
533
+ eventId,
534
+ kind: ASK_JOURNAL_KINDS.REQUESTED,
535
+ askKind: request.kind,
536
+ sessionId: redactIdentifier(request.sessionId) ?? request.sessionId,
537
+ turnId: redactIdentifier(turnId) ?? turnId,
538
+ ...redactIdentifier(request.toolName) !== undefined ? { toolName: redactIdentifier(request.toolName) } : {},
539
+ source: "request",
540
+ at: createdAt
541
+ });
542
+ this.#emit({ type: ASK_FRAME_TYPES.REQUEST, payload: request });
543
+ return request;
544
+ }
545
+ #deadlineOutcome(kind) {
546
+ return kind === "approval" ? "denied" : "cancelled";
547
+ }
548
+ #settle(entry, outcome, options = {}) {
549
+ const eventId = entry.request.eventId;
550
+ this.#disarm(entry.deadlineTimer);
551
+ this.#disarm(entry.graceTimer);
552
+ this.#disarm(entry.hardCapTimer);
553
+ entry.deadlineTimer = undefined;
554
+ entry.graceTimer = undefined;
555
+ entry.hardCapTimer = undefined;
556
+ this.#pending.delete(eventId);
557
+ if (options.ended)
558
+ remember(this.#endedIds, eventId, this.#recordLimit);
559
+ else
560
+ remember(this.#settledIds, eventId, this.#recordLimit);
561
+ if (options.cancelReason !== undefined) {
562
+ this.#emit({ type: ASK_FRAME_TYPES.CANCEL, payload: { eventId, reason: options.cancelReason } });
563
+ }
564
+ const settlement = {
565
+ eventId,
566
+ outcome,
567
+ ...options.code !== undefined ? { code: options.code } : {},
568
+ ...options.message !== undefined ? { message: options.message } : {},
569
+ at: this.#now()
570
+ };
571
+ if (this.#settlementLog.length >= this.#recordLimit)
572
+ this.#settlementLog.shift();
573
+ this.#settlementLog.push(settlement);
574
+ const cancelled = outcome === "cancelled" || options.cancelReason !== undefined;
575
+ this.#writeJournal({
576
+ eventId,
577
+ kind: cancelled ? ASK_JOURNAL_KINDS.CANCELLED : ASK_JOURNAL_KINDS.RESPONDED,
578
+ askKind: entry.request.kind,
579
+ sessionId: redactIdentifier(entry.request.sessionId) ?? entry.request.sessionId,
580
+ turnId: redactIdentifier(entry.turnId) ?? entry.turnId,
581
+ ...redactIdentifier(entry.request.toolName) !== undefined ? { toolName: redactIdentifier(entry.request.toolName) } : {},
582
+ ...options.verdict !== undefined ? { verdict: options.verdict } : {},
583
+ outcome,
584
+ ...options.behavior !== undefined ? { behavior: options.behavior } : {},
585
+ ...summarizeAnswers(options.answers) !== undefined ? { answers: summarizeAnswers(options.answers) } : {},
586
+ ...options.code !== undefined ? { code: options.code } : {},
587
+ ...options.cancelReason !== undefined ? { reason: options.cancelReason } : {},
588
+ source: options.source ?? (cancelled ? "teardown" : "answer"),
589
+ at: settlement.at
590
+ });
591
+ this.#emit({ type: ASK_FRAME_TYPES.SETTLED, payload: { eventId, outcome } });
592
+ return settlement;
593
+ }
594
+ answer(sessionId, rawParams) {
595
+ const parsed = validateAskResponse(rawParams);
596
+ if (!parsed.ok) {
597
+ return { ok: false, code: ASK_ERROR_CODES.INVALID_RESPONSE, message: parsed.message };
598
+ }
599
+ const params = parsed.value;
600
+ const entry = this.#pending.get(params.eventId);
601
+ if (entry === undefined) {
602
+ if (this.#endedIds.has(params.eventId)) {
603
+ return { ok: false, code: ASK_ERROR_CODES.TURN_ENDED, message: "ask belongs to an ended turn/session" };
604
+ }
605
+ if (this.#settledIds.has(params.eventId)) {
606
+ return { ok: false, code: ASK_ERROR_CODES.ALREADY_ANSWERED, message: "ask already answered" };
607
+ }
608
+ return { ok: false, code: ASK_ERROR_CODES.UNKNOWN_REQUEST, message: "unknown eventId" };
609
+ }
610
+ if (entry.deliveredTo !== sessionId) {
611
+ return { ok: false, code: ASK_ERROR_CODES.NOT_ADDRESSEE, message: "ask was delivered to another session" };
612
+ }
613
+ if (params.kind !== entry.request.kind) {
614
+ return { ok: false, code: ASK_ERROR_CODES.INVALID_RESPONSE, message: "response kind does not match the ask" };
615
+ }
616
+ if (entry.request.kind === "approval" && params.verdict === undefined) {
617
+ return { ok: false, code: ASK_ERROR_CODES.INVALID_RESPONSE, message: "approval response requires a verdict" };
618
+ }
619
+ if (entry.request.kind === "questions" && (params.answers === undefined || params.answers.length === 0)) {
620
+ return { ok: false, code: ASK_ERROR_CODES.INVALID_RESPONSE, message: "questions response requires answers" };
621
+ }
622
+ if (params.behavior === "always" && entry.request.escalation !== true) {
623
+ return { ok: false, code: ASK_ERROR_CODES.INVALID_RESPONSE, message: 'behavior:"always" needs a granted escalation' };
624
+ }
625
+ let outcome;
626
+ switch (params.verdict) {
627
+ case "allowed-once":
628
+ outcome = "approved";
629
+ break;
630
+ case "rejected":
631
+ outcome = "denied";
632
+ break;
633
+ case "unavailable":
634
+ outcome = "unavailable";
635
+ break;
636
+ default:
637
+ outcome = "approved";
638
+ }
639
+ if (params.behavior === "always") {
640
+ this.#summary.grant(sessionId, entry.request.toolName ?? params.eventId);
641
+ }
642
+ const settlement = this.#settle(entry, outcome, {
643
+ ...params.verdict !== undefined ? { verdict: params.verdict } : {},
644
+ ...params.behavior !== undefined ? { behavior: params.behavior } : {},
645
+ ...params.answers !== undefined ? { answers: params.answers } : {},
646
+ source: "answer"
647
+ });
648
+ return { ok: true, settlement };
649
+ }
650
+ failClosed(input) {
651
+ const eventId = this.nextEventId(input.turnId);
652
+ const settlement = {
653
+ eventId,
654
+ outcome: "unavailable",
655
+ code: ASK_ERROR_CODES.CHANNEL_UNAVAILABLE,
656
+ message: input.reason ?? "ask channel unavailable (no provider/service)",
657
+ at: this.#now()
658
+ };
659
+ remember(this.#settledIds, eventId, this.#recordLimit);
660
+ this.#settlementLog.push(settlement);
661
+ this.#writeJournal({
662
+ eventId,
663
+ kind: ASK_JOURNAL_KINDS.RESPONDED,
664
+ askKind: input.kind,
665
+ sessionId: redactIdentifier(input.sessionId) ?? input.sessionId,
666
+ turnId: redactIdentifier(input.turnId) ?? input.turnId,
667
+ verdict: "unavailable",
668
+ outcome: "unavailable",
669
+ code: ASK_ERROR_CODES.CHANNEL_UNAVAILABLE,
670
+ source: "fail-closed",
671
+ at: settlement.at
672
+ });
673
+ this.#emit({ type: ASK_FRAME_TYPES.SETTLED, payload: { eventId, outcome: "unavailable" } });
674
+ return { settlement, code: ASK_ERROR_CODES.CHANNEL_UNAVAILABLE };
675
+ }
676
+ markDetached(sessionId) {
677
+ for (const entry of this.#pending.values()) {
678
+ if (entry.deliveredTo !== sessionId || entry.graceTimer !== undefined)
679
+ continue;
680
+ entry.graceTimer = this.#arm(() => {
681
+ this.#settle(entry, "cancelled", {
682
+ cancelReason: "host-abort",
683
+ code: ASK_ERROR_CODES.TURN_ENDED,
684
+ message: "client detached past the grace window",
685
+ source: "teardown"
686
+ });
687
+ }, entry.graceMs);
688
+ }
689
+ }
690
+ markAttached(sessionId) {
691
+ for (const entry of this.#pending.values()) {
692
+ if (entry.deliveredTo !== sessionId || entry.graceTimer === undefined)
693
+ continue;
694
+ this.#disarm(entry.graceTimer);
695
+ entry.graceTimer = undefined;
696
+ }
697
+ }
698
+ clearTurn(turnId, reason = "host-abort") {
699
+ const out = [];
700
+ for (const entry of [...this.#pending.values()]) {
701
+ if (entry.turnId !== turnId)
702
+ continue;
703
+ out.push(this.#settle(entry, "cancelled", { cancelReason: reason, ended: true, message: "turn ended" }));
704
+ }
705
+ return out;
706
+ }
707
+ clearSession(sessionId, reason = "host-abort") {
708
+ const out = [];
709
+ for (const entry of [...this.#pending.values()]) {
710
+ if (entry.deliveredTo !== sessionId)
711
+ continue;
712
+ out.push(this.#settle(entry, "cancelled", { cancelReason: reason, ended: true, message: "session ended" }));
713
+ }
714
+ return out;
715
+ }
716
+ pendingSnapshot(sessionId, emit = false) {
717
+ const asks = [...this.#pending.values()].filter((entry) => entry.deliveredTo === sessionId).map((entry) => ({ ...entry.request }));
718
+ if (emit)
719
+ this.#emit({ type: ASK_FRAME_TYPES.PENDING, payload: { sessionId, asks } });
720
+ return asks;
721
+ }
722
+ dispose() {
723
+ for (const handle of this.#timers)
724
+ clearTimeout(handle);
725
+ this.#timers.clear();
726
+ this.#pending.clear();
727
+ this.#seqByTurn.clear();
728
+ this.#settledIds.clear();
729
+ this.#endedIds.clear();
730
+ this.#settlementLog.length = 0;
731
+ this.#summary.clear();
732
+ this.#logger?.debug?.("[ask-registry] disposed: all timers released");
733
+ }
734
+ }
735
+ var askRegistry = new AskRegistry;
736
+ function createAskRegistry(options = {}) {
737
+ return new AskRegistry(options);
738
+ }
739
+
740
+ // ../bridge/src/append-text.ts
741
+ import { readFileSync, statSync } from "node:fs";
742
+ import { homedir } from "node:os";
743
+ import { join } from "node:path";
744
+ var APPEND_TEXT_MAX_BYTES = 64 * 1024;
745
+ var APPEND_SYSTEM_PRESET_ID = "opentui-append-system";
746
+ function defaultDshHome() {
747
+ return process.env.DSH_HOME || join(homedir(), ".dsh");
748
+ }
749
+ function isContinuationByte(byte) {
750
+ return byte !== undefined && (byte & 192) === 128;
751
+ }
752
+ function decodeUtf8Capped(buf, maxBytes) {
753
+ if (buf.length <= maxBytes)
754
+ return { text: buf.toString("utf8"), truncated: false };
755
+ let end = maxBytes;
756
+ while (end > 0 && isContinuationByte(buf[end]))
757
+ end -= 1;
758
+ return { text: buf.toString("utf8", 0, end), truncated: true };
759
+ }
760
+ function createAppendTextProvider(options = {}) {
761
+ const filePath = join(options.home ?? defaultDshHome(), "APPEND_SYSTEM.md");
762
+ const maxBytes = options.maxBytes ?? APPEND_TEXT_MAX_BYTES;
763
+ const logger = options.logger;
764
+ let cachedMtimeMs;
765
+ let cachedText = "";
766
+ return (_context) => {
767
+ let stat;
768
+ try {
769
+ stat = statSync(filePath);
770
+ } catch {
771
+ return "";
772
+ }
773
+ if (cachedMtimeMs !== undefined && stat.mtimeMs === cachedMtimeMs)
774
+ return cachedText;
775
+ let text;
776
+ try {
777
+ const buf = readFileSync(filePath);
778
+ const decoded = decodeUtf8Capped(buf, maxBytes);
779
+ text = decoded.text;
780
+ if (decoded.truncated) {
781
+ try {
782
+ logger?.warn("[dsh-opentui-bridge] APPEND_SYSTEM.md exceeds %d bytes; truncated at UTF-8 boundary (kept %d bytes; warning is log-only)", maxBytes, Buffer.byteLength(text, "utf8"));
783
+ } catch {}
784
+ }
785
+ } catch {
786
+ return cachedText;
787
+ }
788
+ cachedMtimeMs = stat.mtimeMs;
789
+ cachedText = text;
790
+ return text;
791
+ };
792
+ }
793
+
794
+ // ../bridge/src/append-section.ts
795
+ var APPEND_SECTION_NAME = "dsh-opentui:append-system";
796
+ var APPEND_SECTION_ORDER = 200;
797
+ var NOOP = () => {};
798
+ var EFFECT_LABEL = "dsh-opentui:append-system section";
799
+ function resolveSystemPrompt(ctx) {
800
+ let svc;
801
+ try {
802
+ svc = typeof ctx.get === "function" ? ctx.get("systemPrompt") : undefined;
803
+ if (svc === undefined)
804
+ svc = ctx.systemPrompt;
805
+ } catch {
806
+ svc = undefined;
807
+ }
808
+ return svc !== undefined && typeof svc.section === "function" ? svc : undefined;
809
+ }
810
+ function registerAppendSection(ctx, options = {}) {
811
+ const sp = resolveSystemPrompt(ctx);
812
+ if (sp === undefined) {
813
+ warn(ctx, "[dsh-opentui-bridge] systemPrompt unavailable — append section not registered (plugin stays live)");
814
+ return NOOP;
815
+ }
816
+ const text = options.text ?? createAppendTextProvider({
817
+ logger: ctx.logger,
818
+ ...options.appendText
819
+ });
820
+ let disposer;
821
+ try {
822
+ disposer = sp.section({
823
+ name: APPEND_SECTION_NAME,
824
+ order: APPEND_SECTION_ORDER,
825
+ text,
826
+ interpolate: false
827
+ });
828
+ } catch (err) {
829
+ warn(ctx, "[dsh-opentui-bridge] append section registration contained (plugin stays live): %s", err);
830
+ return NOOP;
831
+ }
832
+ if (typeof disposer !== "function")
833
+ disposer = NOOP;
834
+ let disposed = false;
835
+ const cleanup = () => {
836
+ if (disposed)
837
+ return;
838
+ disposed = true;
839
+ try {
840
+ disposer?.();
841
+ } catch {}
842
+ };
843
+ ctx.effect(() => cleanup, EFFECT_LABEL);
844
+ return cleanup;
845
+ }
846
+ function warn(ctx, format, ...params) {
847
+ try {
848
+ ctx.logger?.warn(format, ...params);
849
+ } catch {}
850
+ }
851
+
852
+ // ../bridge/src/preset-migration.ts
853
+ function presetMentionsAppend(value) {
854
+ if (typeof value === "string")
855
+ return value === APPEND_SYSTEM_PRESET_ID;
856
+ if (Array.isArray(value))
857
+ return value.some(presetMentionsAppend);
858
+ if (value !== null && typeof value === "object") {
859
+ return Object.values(value).some(presetMentionsAppend);
860
+ }
861
+ return false;
862
+ }
863
+ async function readSessionAgentPreset(persistence, sessionId) {
864
+ if (persistence === undefined)
865
+ return;
866
+ let handle;
867
+ try {
868
+ handle = await persistence.open(sessionId, "read");
869
+ return handle?.header?.agentPreset;
870
+ } catch {
871
+ return;
872
+ } finally {
873
+ if (handle !== undefined) {
874
+ try {
875
+ await handle.close();
876
+ } catch {}
877
+ }
878
+ }
879
+ }
880
+ function logLegacyAppendPreset(logger) {
881
+ logger.debug(`[append-system] header.agentPreset="${APPEND_SYSTEM_PRESET_ID}" 为旧版合成 preset id,在本 profile 中不生效(无 agentPresets 服务);append 内容由 bridge section 注入,行为与新建会话一致`);
882
+ }
883
+
884
+ // ../bridge/src/index.ts
885
+ function createBridgeUserMessage(text) {
886
+ return Object.freeze({
887
+ id: randomUUID(),
888
+ role: "user",
889
+ content: Object.freeze([Object.freeze({ type: "text", text })]),
890
+ source: Object.freeze({ kind: "user" })
891
+ });
892
+ }
893
+ function resolveAppExit(ctx) {
894
+ try {
895
+ if (typeof ctx.get === "function") {
896
+ const svc = ctx.get("appExit");
897
+ if (typeof svc === "function")
898
+ return { fn: svc, source: "ctx.get('appExit')" };
899
+ }
900
+ } catch {}
901
+ try {
902
+ const svc = ctx.appExit;
903
+ if (typeof svc === "function")
904
+ return { fn: svc, source: "ctx.appExit" };
905
+ } catch {}
906
+ return;
907
+ }
908
+ var name = "dsh-opentui-bridge";
909
+ var inject = ["agents"];
910
+ function armAppendSection(ctx, options = {}) {
911
+ return registerAppendSection(ctx, options);
912
+ }
913
+ function makeAppendSectionSetup(logger, sessionId) {
914
+ return (agentCtx) => {
915
+ try {
916
+ armAppendSection(agentCtx);
917
+ } catch (err) {
918
+ logger.warn("[dsh-opentui-bridge] append section setup failed for %s (plugin stays live): %s", sessionId, err);
919
+ }
920
+ };
921
+ }
922
+ var askRegistries = new WeakMap;
923
+ function getAskRegistry(ctx) {
924
+ return askRegistries.get(ctx);
925
+ }
926
+ var PROTOCOL_VERSION = 1;
927
+ var STDIO_SWITCH = "DSH_OPENTUI_BRIDGE_STDIO";
928
+ var TERMINAL_TURN_ID_LIMIT = 64;
929
+ function findPackageVersion(entryFile, wantedName) {
930
+ try {
931
+ let dir = dirname(realpathSync(entryFile));
932
+ for (let i = 0;i < 12 && dir !== dirname(dir); i++) {
933
+ try {
934
+ const pkg = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
935
+ if (pkg?.name === wantedName && typeof pkg.version === "string")
936
+ return pkg.version;
937
+ } catch {}
938
+ dir = dirname(dir);
939
+ }
940
+ } catch {}
941
+ return;
942
+ }
943
+ function readBridgeVersion() {
944
+ try {
945
+ const url = new URL("./package.json", import.meta.url);
946
+ const pkg = JSON.parse(readFileSync2(url, "utf8"));
947
+ if (typeof pkg.version === "string")
948
+ return pkg.version;
949
+ } catch {}
950
+ return "unknown";
951
+ }
952
+ function readHostVersion() {
953
+ if (process.argv[1]) {
954
+ const v = findPackageVersion(process.argv[1], "@deepseek-ai/dsh");
955
+ if (v)
956
+ return v;
957
+ }
958
+ try {
959
+ const req = createRequire(import.meta.url);
960
+ const path = req.resolve("@deepseek-ai/dsh/package.json");
961
+ const pkg = JSON.parse(readFileSync2(path, "utf8"));
962
+ if (typeof pkg.version === "string")
963
+ return pkg.version;
964
+ } catch {}
965
+ return "unknown";
966
+ }
967
+ function resolveAgents(ctx) {
968
+ const fromGet = typeof ctx.get === "function" ? ctx.get("agents") : undefined;
969
+ const svc = fromGet ?? ctx.agents;
970
+ return svc !== undefined && typeof svc.create === "function" ? svc : undefined;
971
+ }
972
+ function resolveDefaultModel(ctx) {
973
+ const fromGet = typeof ctx.get === "function" ? ctx.get("agentDefaultModel") : undefined;
974
+ const svc = fromGet ?? ctx.agentDefaultModel;
975
+ return svc !== undefined && typeof svc.currentSelection === "function" ? svc : undefined;
976
+ }
977
+ function resolvePersistence(ctx) {
978
+ const fromGet = typeof ctx.get === "function" ? ctx.get("sessionPersistence") : undefined;
979
+ const svc = fromGet ?? ctx.sessionPersistence;
980
+ return svc !== undefined && typeof svc.open === "function" ? svc : undefined;
981
+ }
982
+ var cachedAppendPluginRecord;
983
+ var appendPluginRecordResolved = false;
984
+ function resolveAppendPluginRecord() {
985
+ if (appendPluginRecordResolved)
986
+ return cachedAppendPluginRecord;
987
+ appendPluginRecordResolved = true;
988
+ const roots = [import.meta.url];
989
+ if (process.argv[1]) {
990
+ try {
991
+ roots.push(realpathSync(process.argv[1]));
992
+ } catch {}
993
+ }
994
+ for (const root of roots) {
995
+ try {
996
+ const req = createRequire(root);
997
+ const mod = req("@deepseek-ai/dsh-session");
998
+ if (typeof mod.appendPluginRecord === "function") {
999
+ cachedAppendPluginRecord = mod.appendPluginRecord;
1000
+ break;
1001
+ }
1002
+ } catch {}
1003
+ }
1004
+ return cachedAppendPluginRecord;
1005
+ }
1006
+ function resolveSessionController(ctx) {
1007
+ let svc;
1008
+ try {
1009
+ svc = typeof ctx.get === "function" ? ctx.get("sessionController") : undefined;
1010
+ if (svc === undefined)
1011
+ svc = ctx.sessionController;
1012
+ } catch {
1013
+ svc = undefined;
1014
+ }
1015
+ return svc !== undefined && typeof svc.list === "function" ? svc : undefined;
1016
+ }
1017
+ function buildAgentOptions(ctx) {
1018
+ const defaults = resolveDefaultModel(ctx);
1019
+ if (defaults === undefined)
1020
+ return {};
1021
+ return {
1022
+ get provider() {
1023
+ return defaults.currentSelection().provider;
1024
+ },
1025
+ get model() {
1026
+ return defaults.currentSelection().model;
1027
+ },
1028
+ get reasoningEffort() {
1029
+ return defaults.currentSelection().reasoningEffort;
1030
+ }
1031
+ };
1032
+ }
1033
+ var HOST_ERROR_CODES = {
1034
+ SessionPersistenceNotFoundError: { code: "SESSION_NOT_FOUND" },
1035
+ SessionAlreadyOwnedError: { code: "SESSION_LOCKED", holder: true },
1036
+ SessionPersistenceCorruptionError: { code: "JOURNAL_CORRUPT" },
1037
+ SessionFormatUnsupportedError: { code: "VERSION_INCOMPATIBLE" }
1038
+ };
1039
+ function mapHostError(err) {
1040
+ const rawName = err !== null && typeof err === "object" ? err.name : undefined;
1041
+ const name = typeof rawName === "string" ? rawName : "";
1042
+ const message = err instanceof Error ? err.message : String(err);
1043
+ const entry = HOST_ERROR_CODES[name];
1044
+ if (entry === undefined)
1045
+ return { code: "INTERNAL", message };
1046
+ let detail;
1047
+ if (entry.holder) {
1048
+ const holder = err !== null && typeof err === "object" ? err.sessionId : undefined;
1049
+ detail = { holder: holder === undefined ? "unknown" : String(holder) };
1050
+ }
1051
+ return { code: entry.code, message, ...detail !== undefined ? { detail } : {} };
1052
+ }
1053
+ function journalCursorOf(binding) {
1054
+ const seq = binding.handle.agent.session?.seq;
1055
+ return typeof seq === "number" && Number.isFinite(seq) ? seq : 0;
1056
+ }
1057
+ var TOKEN_BATCH_MS = 30;
1058
+ var TOKEN_FRAME_BYTE_CAP = 6000;
1059
+ var DEBUG_EVENTS = process.env.DSH_OPENTUI_BRIDGE_DEBUG_EVENTS === "1";
1060
+ function idString(value) {
1061
+ return typeof value === "string" ? value : String(value);
1062
+ }
1063
+ function contentText(content) {
1064
+ if (!Array.isArray(content))
1065
+ return "";
1066
+ let out = "";
1067
+ for (const block of content) {
1068
+ if (block === null || typeof block !== "object")
1069
+ continue;
1070
+ const b = block;
1071
+ if ((b.type === "text" || b.type === "reasoning") && typeof b.text === "string")
1072
+ out += b.text;
1073
+ }
1074
+ return out;
1075
+ }
1076
+ function toolInput(args) {
1077
+ if (typeof args !== "string" || args === "")
1078
+ return;
1079
+ try {
1080
+ return JSON.parse(args);
1081
+ } catch {
1082
+ return args;
1083
+ }
1084
+ }
1085
+ function terminalFromReason(reason) {
1086
+ const r = reason !== null && typeof reason === "object" ? reason : {};
1087
+ const kind = r.kind;
1088
+ if (kind === "error") {
1089
+ const e = r.error !== null && typeof r.error === "object" ? r.error : {};
1090
+ const code = typeof e.code === "string" && e.code !== "" ? e.code : "INTERNAL";
1091
+ const message = typeof e.message === "string" ? e.message : "model turn failed";
1092
+ return { kind: "error", code, message };
1093
+ }
1094
+ if (kind === "aborted") {
1095
+ const cause = r.reason !== null && typeof r.reason === "object" ? r.reason : {};
1096
+ const code = typeof cause.code === "string" && cause.code !== "" ? cause.code : "ABORTED";
1097
+ return { kind: "error", code, message: "turn aborted" };
1098
+ }
1099
+ if (kind === "blocked")
1100
+ return { kind: "error", code: "BLOCKED", message: "turn blocked before a model step" };
1101
+ if (kind === "interrupted")
1102
+ return { kind: "error", code: "INTERRUPTED", message: "turn interrupted" };
1103
+ if (kind === "forked")
1104
+ return { kind: "error", code: "FORKED", message: "turn closed by fork" };
1105
+ return { kind: "end" };
1106
+ }
1107
+ function parseRequest(raw) {
1108
+ let value;
1109
+ try {
1110
+ value = JSON.parse(raw);
1111
+ } catch {
1112
+ throw { code: "BAD_FRAME", message: "frame is not valid JSON" };
1113
+ }
1114
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1115
+ throw { code: "BAD_FRAME", message: "frame must be a JSON object" };
1116
+ }
1117
+ const obj = value;
1118
+ const id = typeof obj.id === "string" || typeof obj.id === "number" ? obj.id : null;
1119
+ if (typeof obj.method !== "string" || obj.method.trim() === "") {
1120
+ throw { code: "BAD_FRAME", message: "request is missing a method", id };
1121
+ }
1122
+ const params = obj.params !== null && typeof obj.params === "object" && !Array.isArray(obj.params) ? obj.params : {};
1123
+ return { id, method: obj.method, params };
1124
+ }
1125
+ function apply(ctx, config) {
1126
+ const logger = ctx.logger;
1127
+ if (process.env[STDIO_SWITCH] !== "1") {
1128
+ logger.info("[dsh-opentui-bridge] starting (skeleton)");
1129
+ return ctx.effect(() => () => {
1130
+ logger.info("[dsh-opentui-bridge] disposed");
1131
+ }, "dsh-opentui-bridge: lifecycle");
1132
+ }
1133
+ const bridgeVersion = readBridgeVersion();
1134
+ const hostVersion = readHostVersion();
1135
+ logger.info(`[dsh-opentui-bridge] stdio protocol active (protocolVersion=${PROTOCOL_VERSION}, bridge=${bridgeVersion}, host=${hostVersion})`);
1136
+ let buffer = "";
1137
+ let closing = false;
1138
+ let awaitingDrain = false;
1139
+ let binding;
1140
+ let inFlightTurnId;
1141
+ let dispatchChain = Promise.resolve();
1142
+ let eofSeen = false;
1143
+ let activeTurn;
1144
+ const terminalTurnIds = new Set;
1145
+ let unsubSessionEvent;
1146
+ let unsubStream;
1147
+ let unsubApprovalAnswerer;
1148
+ let unsubQuestionsAnswerer;
1149
+ function writeFrame(frame) {
1150
+ if (closing)
1151
+ return;
1152
+ const line = `${JSON.stringify(frame)}
1153
+ `;
1154
+ let writable = true;
1155
+ try {
1156
+ writable = process.stdout.write(line, "utf8");
1157
+ } catch (err) {
1158
+ logger.error("[dsh-opentui-bridge] stdout write failed: %s", err);
1159
+ return;
1160
+ }
1161
+ if (!writable && !awaitingDrain) {
1162
+ awaitingDrain = true;
1163
+ process.stdin.pause();
1164
+ process.stdout.once("drain", () => {
1165
+ awaitingDrain = false;
1166
+ if (!closing)
1167
+ process.stdin.resume();
1168
+ });
1169
+ }
1170
+ }
1171
+ function replyOk(id, result) {
1172
+ writeFrame({ id, ok: true, result });
1173
+ }
1174
+ function replyError(id, code, message, detail) {
1175
+ const error = { code, message };
1176
+ if (detail !== undefined)
1177
+ error.detail = detail;
1178
+ writeFrame({ id, ok: false, error });
1179
+ }
1180
+ function emitEvent(type, payload) {
1181
+ writeFrame({ type, payload });
1182
+ }
1183
+ const pendingAnswerers = new Map;
1184
+ function settleAnswerer(eventId, settlement) {
1185
+ const pending = pendingAnswerers.get(eventId);
1186
+ if (pending === undefined)
1187
+ return;
1188
+ pendingAnswerers.delete(eventId);
1189
+ pending.resolve(settlement);
1190
+ }
1191
+ function waitForAnswerer(eventId, signal) {
1192
+ return new Promise((resolve) => {
1193
+ const pending = { resolve };
1194
+ pendingAnswerers.set(eventId, pending);
1195
+ if (signal !== undefined) {
1196
+ if (signal.aborted) {
1197
+ settleAnswerer(eventId, { outcome: "cancelled" });
1198
+ } else {
1199
+ const original = pending.resolve;
1200
+ const onAbort = () => settleAnswerer(eventId, { outcome: "cancelled" });
1201
+ pending.resolve = (settlement) => {
1202
+ signal.removeEventListener("abort", onAbort);
1203
+ original(settlement);
1204
+ };
1205
+ signal.addEventListener("abort", onAbort, { once: true });
1206
+ }
1207
+ }
1208
+ });
1209
+ }
1210
+ function writeAskJournal(event) {
1211
+ const session = binding?.handle.agent.session;
1212
+ if (session === undefined)
1213
+ return;
1214
+ const append = resolveAppendPluginRecord();
1215
+ if (append === undefined) {
1216
+ logger.debug("[dsh-opentui-bridge] ask journal writer unavailable; event %s not persisted", event.eventId);
1217
+ return;
1218
+ }
1219
+ const type = askPluginRecordType(event.kind);
1220
+ try {
1221
+ append(session, type, event);
1222
+ const bytes = Buffer.byteLength(JSON.stringify(event), "utf8");
1223
+ logger.info("[dsh-opentui-bridge] ask journal append type=%s eventId=%s bytes=%d session=%s", type, event.eventId, bytes, event.sessionId);
1224
+ } catch (err) {
1225
+ logger.warn("[dsh-opentui-bridge] ask journal append failed (decision unchanged): %s", err);
1226
+ }
1227
+ }
1228
+ const ask = new AskRegistry({
1229
+ logger,
1230
+ journal: writeAskJournal,
1231
+ sink: (frame) => {
1232
+ emitEvent(frame.type, frame.payload);
1233
+ if (frame.type === ASK_FRAME_TYPES.SETTLED) {
1234
+ const settled = frame.payload;
1235
+ const pending = pendingAnswerers.get(settled.eventId);
1236
+ settleAnswerer(settled.eventId, {
1237
+ outcome: settled.outcome,
1238
+ ...pending?.params !== undefined ? { params: pending.params } : {}
1239
+ });
1240
+ }
1241
+ }
1242
+ });
1243
+ askRegistries.set(ctx, ask);
1244
+ function ensureStarted(state) {
1245
+ if (state.started)
1246
+ return;
1247
+ state.started = true;
1248
+ emitEvent("turn.start", { turnId: state.turnId, sessionId: state.sessionId });
1249
+ }
1250
+ function flushPending(state) {
1251
+ if (state.pendingText !== "") {
1252
+ emitEvent("turn.token", { turnId: state.turnId, kind: "text", text: state.pendingText });
1253
+ state.tokenFrameCount += 1;
1254
+ state.pendingText = "";
1255
+ }
1256
+ if (state.pendingReasoning !== "") {
1257
+ emitEvent("turn.token", { turnId: state.turnId, kind: "reasoning", text: state.pendingReasoning });
1258
+ state.tokenFrameCount += 1;
1259
+ state.pendingReasoning = "";
1260
+ }
1261
+ }
1262
+ function scheduleFlush(state) {
1263
+ if (state.batchTimer !== undefined)
1264
+ return;
1265
+ state.batchTimer = setTimeout(() => {
1266
+ state.batchTimer = undefined;
1267
+ if (!state.ended && activeTurn === state)
1268
+ flushPending(state);
1269
+ }, TOKEN_BATCH_MS);
1270
+ state.batchTimer.unref?.();
1271
+ }
1272
+ function appendDelta(state, kind, text) {
1273
+ if (text === "")
1274
+ return;
1275
+ state.deltaCount += 1;
1276
+ if (kind === "text") {
1277
+ state.textAcc += text;
1278
+ if (state.pendingText !== "" && Buffer.byteLength(state.pendingText + text, "utf8") > TOKEN_FRAME_BYTE_CAP) {
1279
+ flushPending(state);
1280
+ }
1281
+ state.pendingText += text;
1282
+ } else {
1283
+ state.reasoningAcc += text;
1284
+ if (state.pendingReasoning !== "" && Buffer.byteLength(state.pendingReasoning + text, "utf8") > TOKEN_FRAME_BYTE_CAP) {
1285
+ flushPending(state);
1286
+ }
1287
+ state.pendingReasoning += text;
1288
+ }
1289
+ scheduleFlush(state);
1290
+ }
1291
+ function rememberTerminalTurnId(turnId) {
1292
+ terminalTurnIds.add(turnId);
1293
+ while (terminalTurnIds.size > TERMINAL_TURN_ID_LIMIT) {
1294
+ const oldest = terminalTurnIds.values().next().value;
1295
+ if (oldest === undefined)
1296
+ break;
1297
+ terminalTurnIds.delete(oldest);
1298
+ }
1299
+ }
1300
+ function finalizeTurn(state, terminal) {
1301
+ if (state.ended)
1302
+ return;
1303
+ state.ended = true;
1304
+ if (state.batchTimer !== undefined) {
1305
+ clearTimeout(state.batchTimer);
1306
+ state.batchTimer = undefined;
1307
+ }
1308
+ ensureStarted(state);
1309
+ flushPending(state);
1310
+ if (terminal.kind === "end") {
1311
+ emitEvent("turn.end", {
1312
+ turnId: state.turnId,
1313
+ text: state.textAcc,
1314
+ ...state.reasoningAcc !== "" ? { reasoning: state.reasoningAcc } : {},
1315
+ ...state.usage !== undefined ? { usage: state.usage } : {}
1316
+ });
1317
+ } else {
1318
+ emitEvent("turn.error", { turnId: state.turnId, code: terminal.code, message: terminal.message });
1319
+ }
1320
+ if (activeTurn === state)
1321
+ activeTurn = undefined;
1322
+ if (inFlightTurnId === state.turnId)
1323
+ inFlightTurnId = undefined;
1324
+ rememberTerminalTurnId(state.turnId);
1325
+ ask.clearTurn(state.turnId);
1326
+ logger.info("[dsh-opentui-bridge] turn %s finalized kind=%s textChars=%d deltas=%d tokenFrames=%d", state.turnId, terminal.kind, state.textAcc.length, state.deltaCount, state.tokenFrameCount);
1327
+ if (DEBUG_EVENTS) {
1328
+ logger.warn("[bridge:stat] turn=%s deltas=%d tokenFrames=%d textChars=%d reasonChars=%d", state.turnId, state.deltaCount, state.tokenFrameCount, state.textAcc.length, state.reasoningAcc.length);
1329
+ }
1330
+ }
1331
+ function onSessionEvent(session, event) {
1332
+ const state = activeTurn;
1333
+ const s = session;
1334
+ const sessionId = idString(s?.id);
1335
+ const e = event;
1336
+ const type = typeof e?.type === "string" ? e.type : "";
1337
+ const data = e?.data !== null && typeof e?.data === "object" ? e.data : {};
1338
+ if (type === "subagent/catalog") {
1339
+ const boundId = binding?.sessionId;
1340
+ if (sessionId !== boundId)
1341
+ return;
1342
+ const childId = typeof data.childId === "string" ? data.childId : "";
1343
+ if (!childId)
1344
+ return;
1345
+ const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
1346
+ const label = typeof data.label === "string" && data.label !== "" ? data.label : typeof data.name === "string" ? data.name : "";
1347
+ emitEvent("agent.spawn", {
1348
+ turnId,
1349
+ sessionId: boundId,
1350
+ childId,
1351
+ label,
1352
+ runId: `catalog:${childId}`,
1353
+ seq: 0,
1354
+ ...typeof data.childCreatedAt === "number" ? { childCreatedAt: data.childCreatedAt } : {}
1355
+ });
1356
+ return;
1357
+ }
1358
+ if (type === "tool-workflow/agent-start" || type === "tool-workflow/agent-end") {
1359
+ const boundId = binding?.sessionId;
1360
+ if (sessionId !== boundId)
1361
+ return;
1362
+ const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
1363
+ if (type === "tool-workflow/agent-start") {
1364
+ const childId = idString(data.childId);
1365
+ if (!childId)
1366
+ return;
1367
+ emitEvent("agent.spawn", {
1368
+ turnId,
1369
+ sessionId: boundId,
1370
+ childId,
1371
+ label: typeof data.label === "string" ? data.label : "",
1372
+ runId: idString(data.runId),
1373
+ seq: typeof data.seq === "number" ? data.seq : -1
1374
+ });
1375
+ } else {
1376
+ emitEvent("agent.settle", {
1377
+ turnId,
1378
+ sessionId: boundId,
1379
+ runId: idString(data.runId),
1380
+ seq: typeof data.seq === "number" ? data.seq : -1,
1381
+ outcome: typeof data.outcome === "string" ? data.outcome : "completed"
1382
+ });
1383
+ }
1384
+ return;
1385
+ }
1386
+ if (state === undefined || state.ended)
1387
+ return;
1388
+ if (sessionId !== state.sessionId)
1389
+ return;
1390
+ if (DEBUG_EVENTS) {
1391
+ logger.info("[bridge:ev] session=%s type=%s turn=%s", state.sessionId, type, String(data.turn));
1392
+ }
1393
+ if (type === "turn/start") {
1394
+ if (typeof data.turn === "number")
1395
+ state.numericTurn = data.turn;
1396
+ ensureStarted(state);
1397
+ return;
1398
+ }
1399
+ if (state.numericTurn !== undefined && typeof data.turn === "number" && data.turn !== state.numericTurn)
1400
+ return;
1401
+ if (type === "assistant/message") {
1402
+ flushPending(state);
1403
+ if (data.usage !== undefined)
1404
+ state.usage = data.usage;
1405
+ return;
1406
+ }
1407
+ if (type === "tool/call") {
1408
+ flushPending(state);
1409
+ ensureStarted(state);
1410
+ const callId = idString(data.callId);
1411
+ const name = typeof data.name === "string" ? data.name : "";
1412
+ if (callId !== "undefined")
1413
+ state.toolNames.set(callId, name);
1414
+ const input = toolInput(data.arguments);
1415
+ emitEvent("turn.tool", {
1416
+ turnId: state.turnId,
1417
+ name,
1418
+ ...callId !== "undefined" && callId !== "" ? { callId } : {},
1419
+ ...input !== undefined ? { input } : {}
1420
+ });
1421
+ return;
1422
+ }
1423
+ if (type === "tool/result") {
1424
+ flushPending(state);
1425
+ ensureStarted(state);
1426
+ const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
1427
+ const callId = idString(message?.toolCallId);
1428
+ const name = state.toolNames.get(callId) ?? "";
1429
+ emitEvent("turn.tool", {
1430
+ turnId: state.turnId,
1431
+ name,
1432
+ ...callId !== "undefined" && callId !== "" ? { callId } : {},
1433
+ output: contentText(message?.content),
1434
+ isError: data.isError === true || message?.isError === true
1435
+ });
1436
+ return;
1437
+ }
1438
+ if (type === "turn/end") {
1439
+ const terminal = terminalFromReason(data.reason);
1440
+ finalizeTurn(state, terminal);
1441
+ }
1442
+ }
1443
+ function onAssistantStream(payload) {
1444
+ const state = activeTurn;
1445
+ if (state === undefined || state.ended)
1446
+ return;
1447
+ const p = payload;
1448
+ const agent = p?.agent;
1449
+ if (idString(agent?.id) !== state.sessionId)
1450
+ return;
1451
+ const frame = p?.frame !== null && typeof p?.frame === "object" ? p.frame : {};
1452
+ if (frame.type === "start") {
1453
+ if (typeof frame.turn === "number")
1454
+ state.numericTurn = frame.turn;
1455
+ return;
1456
+ }
1457
+ if (frame.type !== "chunk")
1458
+ return;
1459
+ const chunk = frame.chunk !== null && typeof frame.chunk === "object" ? frame.chunk : {};
1460
+ const ctype = chunk.type;
1461
+ if (ctype !== "text-delta" && ctype !== "reasoning-delta")
1462
+ return;
1463
+ const text = typeof chunk.text === "string" ? chunk.text : "";
1464
+ if (text === "")
1465
+ return;
1466
+ if (DEBUG_EVENTS) {
1467
+ logger.info("[bridge:ev] stream session=%s chunk=%s chars=%d", state.sessionId, ctype, text.length);
1468
+ }
1469
+ ensureStarted(state);
1470
+ appendDelta(state, ctype === "text-delta" ? "text" : "reasoning", text);
1471
+ }
1472
+ function askTarget(agent) {
1473
+ const state = activeTurn;
1474
+ if (state === undefined || state.ended || binding === undefined)
1475
+ return;
1476
+ if (state.sessionId !== binding.sessionId)
1477
+ return;
1478
+ const agentSessionId = agent?.session?.id;
1479
+ if (agentSessionId !== undefined && idString(agentSessionId) !== binding.sessionId)
1480
+ return;
1481
+ return { turn: state, sessionId: binding.sessionId };
1482
+ }
1483
+ const FAIL_CLOSED_UNKNOWN_SESSION = "unknown";
1484
+ function failClosedAsk(kind, turnId, sessionId, reason) {
1485
+ const result = ask.failClosed({ turnId, sessionId, kind, reason });
1486
+ logger.warn("[dsh-opentui-bridge] ask fail-closed kind=%s session=%s eventId=%s code=%s reason=%s", kind, sessionId, result.settlement.eventId, result.code, reason);
1487
+ }
1488
+ async function onApprovalRequest(raw, _next) {
1489
+ const req = raw !== null && typeof raw === "object" ? raw : {};
1490
+ const target = askTarget(req.agent);
1491
+ if (target === undefined) {
1492
+ failClosedAsk("approval", "no-turn", binding?.sessionId ?? FAIL_CLOSED_UNKNOWN_SESSION, "no open in-flight turn to deliver an approval ask");
1493
+ return "unavailable";
1494
+ }
1495
+ const toolName = typeof req.toolName === "string" && req.toolName !== "" ? req.toolName : undefined;
1496
+ if (toolName !== undefined && ask.hasGrant(target.sessionId, toolName)) {
1497
+ const grantedEventId = ask.recordSummaryDecision(target.turn.turnId, {
1498
+ sessionId: target.sessionId,
1499
+ askKind: "approval",
1500
+ toolName
1501
+ });
1502
+ logger.info("[dsh-opentui-bridge] ask always-grant from session summary: session=%s tool=%s eventId=%s (no card)", target.sessionId, toolName, grantedEventId);
1503
+ return "allowed-once";
1504
+ }
1505
+ const callId = req.callId === undefined ? undefined : idString(req.callId);
1506
+ const reason = typeof req.reason === "string" && req.reason !== "" ? req.reason : undefined;
1507
+ let request;
1508
+ try {
1509
+ request = ask.create(target.turn.turnId, {
1510
+ sessionId: target.sessionId,
1511
+ kind: "approval",
1512
+ ...toolName !== undefined ? { toolName } : {},
1513
+ ...callId !== undefined ? { callId } : {},
1514
+ ...reason !== undefined ? { reason } : {},
1515
+ escalation: true
1516
+ });
1517
+ } catch (err) {
1518
+ logger.error("[dsh-opentui-bridge] ask.create(approval) failed: %s", err);
1519
+ failClosedAsk("approval", target.turn.turnId, target.sessionId, "ask.create(approval) threw");
1520
+ return "unavailable";
1521
+ }
1522
+ const settled = await waitForAnswerer(request.eventId, req.signal);
1523
+ switch (settled.outcome) {
1524
+ case "approved":
1525
+ return "allowed-once";
1526
+ case "denied":
1527
+ return "rejected";
1528
+ case "cancelled":
1529
+ return "cancelled";
1530
+ case "unavailable":
1531
+ return "unavailable";
1532
+ }
1533
+ }
1534
+ async function onUserQuestionsRequest(raw, _next) {
1535
+ const req = raw !== null && typeof raw === "object" ? raw : {};
1536
+ const target = askTarget(req.agent);
1537
+ if (target === undefined) {
1538
+ failClosedAsk("questions", "no-turn", binding?.sessionId ?? FAIL_CLOSED_UNKNOWN_SESSION, "no open in-flight turn to deliver a questions ask");
1539
+ throw new Error("ASK_CHANNEL_UNAVAILABLE: no in-flight turn to deliver user questions");
1540
+ }
1541
+ const questions = (req.questions ?? []).map((q) => {
1542
+ const id = q.id === undefined ? "" : idString(q.id);
1543
+ const prompt = q.question ?? q.header ?? id;
1544
+ return {
1545
+ id,
1546
+ prompt: idString(prompt),
1547
+ ...typeof q.header === "string" && q.header !== "" ? { header: q.header } : {},
1548
+ ...typeof q.description === "string" && q.description !== "" ? { description: q.description } : {},
1549
+ ...typeof q.detail === "string" && q.detail !== "" ? { detail: q.detail } : {},
1550
+ options: (q.options ?? []).map((option) => ({
1551
+ label: option.label === undefined ? "" : idString(option.label),
1552
+ ...typeof option.description === "string" && option.description !== "" ? { description: option.description } : {}
1553
+ })),
1554
+ ...q.multiSelect === true ? { multiSelect: true } : {}
1555
+ };
1556
+ });
1557
+ const callId = req.wait?.callId === undefined ? undefined : idString(req.wait.callId);
1558
+ let request;
1559
+ try {
1560
+ request = ask.create(target.turn.turnId, {
1561
+ sessionId: target.sessionId,
1562
+ kind: "questions",
1563
+ questions,
1564
+ ...callId !== undefined ? { callId } : {}
1565
+ });
1566
+ } catch (err) {
1567
+ logger.error("[dsh-opentui-bridge] ask.create(questions) failed: %s", err);
1568
+ failClosedAsk("questions", target.turn.turnId, target.sessionId, "ask.create(questions) threw");
1569
+ throw new Error("ASK_CHANNEL_UNAVAILABLE: ask.create(questions) failed");
1570
+ }
1571
+ const settled = await waitForAnswerer(request.eventId, req.signal);
1572
+ if (settled.outcome !== "approved" || settled.params?.answers === undefined || settled.params.answers.length === 0) {
1573
+ throw new Error(`ASK_CHANNEL_UNAVAILABLE: user questions settled ${settled.outcome}`);
1574
+ }
1575
+ return {
1576
+ answers: settled.params.answers.map((answer) => ({
1577
+ id: answer.id,
1578
+ selected: [...answer.selected],
1579
+ ...answer.custom !== undefined ? { custom: answer.custom } : {}
1580
+ }))
1581
+ };
1582
+ }
1583
+ function armAskAnswerers() {
1584
+ if (typeof ctx.on !== "function") {
1585
+ logger.warn("[dsh-opentui-bridge] ctx.on unavailable — ask answerers not registered (host waterfall stays fail-closed)");
1586
+ return;
1587
+ }
1588
+ try {
1589
+ unsubApprovalAnswerer = ctx.on("approval/request", onApprovalRequest);
1590
+ unsubQuestionsAnswerer = ctx.on("user-questions/request", onUserQuestionsRequest);
1591
+ logger.info("[dsh-opentui-bridge] ask answerers armed (approval + user-questions)");
1592
+ } catch (err) {
1593
+ unsubApprovalAnswerer = undefined;
1594
+ unsubQuestionsAnswerer = undefined;
1595
+ logger.warn("[dsh-opentui-bridge] ask answerer registration contained (plugin stays live): %s", err);
1596
+ }
1597
+ }
1598
+ function armTurnSubscriptions() {
1599
+ if (typeof ctx.on !== "function") {
1600
+ logger.warn("[dsh-opentui-bridge] ctx.on unavailable — turn event stream disabled");
1601
+ return;
1602
+ }
1603
+ unsubSessionEvent = ctx.on("session/event", onSessionEvent);
1604
+ unsubStream = ctx.on("agent/assistant-stream", onAssistantStream);
1605
+ logger.info("[dsh-opentui-bridge] turn event subscriptions armed");
1606
+ }
1607
+ function clearTurnSubscriptions() {
1608
+ try {
1609
+ unsubSessionEvent?.();
1610
+ } catch {}
1611
+ try {
1612
+ unsubStream?.();
1613
+ } catch {}
1614
+ unsubSessionEvent = undefined;
1615
+ unsubStream = undefined;
1616
+ if (activeTurn !== undefined && activeTurn.batchTimer !== undefined) {
1617
+ clearTimeout(activeTurn.batchTimer);
1618
+ }
1619
+ activeTurn = undefined;
1620
+ }
1621
+ async function disposeBinding(current) {
1622
+ if (activeTurn !== undefined && activeTurn.sessionId === current.sessionId && !activeTurn.ended) {
1623
+ finalizeTurn(activeTurn, {
1624
+ kind: "error",
1625
+ code: "SESSION_CLOSED",
1626
+ message: "turn terminated because its session was closed or replaced"
1627
+ });
1628
+ }
1629
+ ask.clearSession(current.sessionId);
1630
+ ask.clearSessionGrants(current.sessionId);
1631
+ if (activeTurn !== undefined && activeTurn.sessionId === current.sessionId) {
1632
+ ask.clearTurn(activeTurn.turnId);
1633
+ }
1634
+ binding = undefined;
1635
+ inFlightTurnId = undefined;
1636
+ terminalTurnIds.clear();
1637
+ if (activeTurn !== undefined && activeTurn.sessionId === current.sessionId) {
1638
+ if (activeTurn.batchTimer !== undefined)
1639
+ clearTimeout(activeTurn.batchTimer);
1640
+ activeTurn = undefined;
1641
+ }
1642
+ try {
1643
+ await current.handle.dispose();
1644
+ } catch (err) {
1645
+ logger.warn("[dsh-opentui-bridge] handle dispose failed: %s", err);
1646
+ }
1647
+ }
1648
+ function pushResumePendingSnapshot(sessionId) {
1649
+ ask.pendingSnapshot(sessionId, true);
1650
+ }
1651
+ function restoreSessionGrantsFromJournal(sessionId) {
1652
+ (async () => {
1653
+ let handle;
1654
+ try {
1655
+ const persistence = resolvePersistence(ctx);
1656
+ if (persistence === undefined)
1657
+ return;
1658
+ handle = await persistence.open(sessionId, "read");
1659
+ const rows = [];
1660
+ let offset = 0;
1661
+ for (;; ) {
1662
+ const batch = await handle.read(offset);
1663
+ const slice = batch.events ?? [];
1664
+ if (slice.length === 0)
1665
+ break;
1666
+ for (const event of slice) {
1667
+ rows.push({
1668
+ type: typeof event.type === "string" ? event.type : "",
1669
+ payload: event.data
1670
+ });
1671
+ }
1672
+ offset += slice.length;
1673
+ }
1674
+ if (binding?.sessionId !== sessionId)
1675
+ return;
1676
+ const tools = alwaysGrantToolsFromJournal(sessionId, rows);
1677
+ if (tools.length > 0) {
1678
+ ask.restoreSessionGrants(sessionId, tools);
1679
+ logger.info("[dsh-opentui-bridge] restored %d always-grant(s) from journal session=%s tools=%s", tools.length, sessionId, tools.join(","));
1680
+ }
1681
+ } catch (err) {
1682
+ logger.warn("[dsh-opentui-bridge] journal grant reconstruction skipped (summary stays empty): %s", err);
1683
+ } finally {
1684
+ if (handle !== undefined) {
1685
+ try {
1686
+ await handle.close();
1687
+ } catch {}
1688
+ }
1689
+ }
1690
+ })();
1691
+ }
1692
+ async function handleOpen(req) {
1693
+ const agents = resolveAgents(ctx);
1694
+ if (agents === undefined) {
1695
+ replyError(req.id, "INTERNAL", "agent registry service unavailable");
1696
+ return;
1697
+ }
1698
+ const mode = req.params.mode;
1699
+ const targetId = mode === "resume" ? req.params.id : undefined;
1700
+ const replace = req.params.replace === true;
1701
+ let previousSessionId;
1702
+ if (binding !== undefined) {
1703
+ if (mode === "resume" && targetId === binding.sessionId) {
1704
+ replyOk(req.id, { sessionId: binding.sessionId, journalCursor: journalCursorOf(binding) });
1705
+ pushResumePendingSnapshot(binding.sessionId);
1706
+ restoreSessionGrantsFromJournal(binding.sessionId);
1707
+ return;
1708
+ }
1709
+ if (!replace) {
1710
+ replyError(req.id, "ALREADY_OPEN", "a session is already open; call session.close before opening another", { openSessionId: binding.sessionId });
1711
+ return;
1712
+ }
1713
+ if (mode !== "resume" || typeof targetId !== "string" || targetId === "") {
1714
+ replyError(req.id, "BAD_PARAMS", 'session.open replace requires mode="resume" with an explicitly named id');
1715
+ return;
1716
+ }
1717
+ previousSessionId = binding.sessionId;
1718
+ await disposeBinding(binding);
1719
+ logger.info("[dsh-opentui-bridge] session.open replace closed previous session %s", previousSessionId);
1720
+ }
1721
+ try {
1722
+ let sessionId;
1723
+ let handle;
1724
+ if (mode === "new") {
1725
+ sessionId = randomUUID();
1726
+ handle = await agents.create({
1727
+ sessionId,
1728
+ meta: { cwd: process.cwd() },
1729
+ agentOptions: buildAgentOptions(ctx),
1730
+ setup: makeAppendSectionSetup(logger, sessionId)
1731
+ });
1732
+ } else if (mode === "resume") {
1733
+ const id = req.params.id;
1734
+ if (typeof id !== "string" || id === "") {
1735
+ replyError(req.id, "BAD_PARAMS", "session.open resume requires a non-empty id");
1736
+ return;
1737
+ }
1738
+ const live = agents.get(id);
1739
+ if (live !== undefined) {
1740
+ logger.info("[dsh-opentui-bridge] session.open adopt live %s", id);
1741
+ handle = { agent: live, dispose: async () => {} };
1742
+ } else {
1743
+ try {
1744
+ const preset = await readSessionAgentPreset(resolvePersistence(ctx), id);
1745
+ if (presetMentionsAppend(preset))
1746
+ logLegacyAppendPreset(logger);
1747
+ } catch {}
1748
+ logger.info("[dsh-opentui-bridge] session.open resume %s", id);
1749
+ handle = await agents.resume({
1750
+ resumeSessionId: id,
1751
+ agentOptions: buildAgentOptions(ctx),
1752
+ setup: makeAppendSectionSetup(logger, id)
1753
+ });
1754
+ }
1755
+ sessionId = id;
1756
+ } else {
1757
+ replyError(req.id, "BAD_PARAMS", 'session.open mode must be "new" or "resume"');
1758
+ return;
1759
+ }
1760
+ binding = { sessionId, handle };
1761
+ logger.info("[dsh-opentui-bridge] session.open ok id=%s cursor=%d", sessionId, journalCursorOf(binding));
1762
+ replyOk(req.id, {
1763
+ sessionId,
1764
+ journalCursor: journalCursorOf(binding),
1765
+ ...previousSessionId !== undefined ? { previousSessionId } : {}
1766
+ });
1767
+ if (mode === "resume") {
1768
+ pushResumePendingSnapshot(sessionId);
1769
+ restoreSessionGrantsFromJournal(sessionId);
1770
+ }
1771
+ } catch (err) {
1772
+ logger.error("[dsh-opentui-bridge] session.open failed: %s", err);
1773
+ const mapped = mapHostError(err);
1774
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
1775
+ }
1776
+ }
1777
+ async function handleSend(req) {
1778
+ if (binding === undefined) {
1779
+ replyError(req.id, "SESSION_NOT_OPEN", "no open session; call session.open first");
1780
+ return;
1781
+ }
1782
+ if (inFlightTurnId !== undefined) {
1783
+ replyError(req.id, "TURN_BUSY", "a turn is already in flight for this session", { turnId: inFlightTurnId });
1784
+ return;
1785
+ }
1786
+ const text = req.params.text;
1787
+ if (typeof text !== "string") {
1788
+ replyError(req.id, "BAD_PARAMS", "session.send requires a text string");
1789
+ return;
1790
+ }
1791
+ const agent = binding.handle.agent;
1792
+ const sessionId = binding.sessionId;
1793
+ const message = createBridgeUserMessage(text);
1794
+ const turnId = randomUUID();
1795
+ inFlightTurnId = turnId;
1796
+ const state = {
1797
+ turnId,
1798
+ sessionId,
1799
+ started: false,
1800
+ ended: false,
1801
+ textAcc: "",
1802
+ reasoningAcc: "",
1803
+ pendingText: "",
1804
+ pendingReasoning: "",
1805
+ toolNames: new Map,
1806
+ deltaCount: 0,
1807
+ tokenFrameCount: 0
1808
+ };
1809
+ activeTurn = state;
1810
+ const clearInFlight = () => {
1811
+ if (inFlightTurnId === turnId)
1812
+ inFlightTurnId = undefined;
1813
+ };
1814
+ try {
1815
+ if (agent.status === "running") {
1816
+ try {
1817
+ agent.steer(message);
1818
+ } catch {
1819
+ agent.followup(message);
1820
+ }
1821
+ } else {
1822
+ agent.followup(message);
1823
+ }
1824
+ ensureStarted(state);
1825
+ agent.whenIdle().then(() => {
1826
+ const safety = setTimeout(() => {
1827
+ if (inFlightTurnId === turnId) {
1828
+ logger.warn("[dsh-opentui-bridge] turn %s idle with no terminal frame; finalizing", turnId);
1829
+ if (activeTurn === state && !state.ended) {
1830
+ finalizeTurn(state, {
1831
+ kind: "error",
1832
+ code: "INTERNAL",
1833
+ message: "no terminal frame received before the idle safety net fired"
1834
+ });
1835
+ }
1836
+ clearInFlight();
1837
+ }
1838
+ }, 2000);
1839
+ safety.unref?.();
1840
+ }, (err) => {
1841
+ if (activeTurn === state) {
1842
+ finalizeTurn(state, {
1843
+ kind: "error",
1844
+ code: "INTERNAL",
1845
+ message: err instanceof Error ? err.message : String(err)
1846
+ });
1847
+ }
1848
+ clearInFlight();
1849
+ });
1850
+ logger.info("[dsh-opentui-bridge] session.send ok turnId=%s sessionId=%s", turnId, sessionId);
1851
+ replyOk(req.id, { turnId });
1852
+ } catch (err) {
1853
+ if (activeTurn === state) {
1854
+ finalizeTurn(state, {
1855
+ kind: "error",
1856
+ code: "INTERNAL",
1857
+ message: err instanceof Error ? err.message : String(err)
1858
+ });
1859
+ }
1860
+ clearInFlight();
1861
+ logger.error("[dsh-opentui-bridge] session.send failed: %s", err);
1862
+ replyError(req.id, "INTERNAL", err instanceof Error ? err.message : String(err));
1863
+ }
1864
+ }
1865
+ async function handleClose(req) {
1866
+ if (binding === undefined) {
1867
+ replyError(req.id, "SESSION_NOT_OPEN", "no open session");
1868
+ return;
1869
+ }
1870
+ const current = binding;
1871
+ await disposeBinding(current);
1872
+ logger.info("[dsh-opentui-bridge] session.close ok id=%s", current.sessionId);
1873
+ replyOk(req.id, { sessionId: current.sessionId });
1874
+ }
1875
+ function handleAbort(req) {
1876
+ const requested = req.params.turnId;
1877
+ if (typeof requested !== "string" || requested === "") {
1878
+ replyError(req.id, "BAD_PARAMS", "turn.abort requires a non-empty turnId string");
1879
+ return;
1880
+ }
1881
+ const state = activeTurn;
1882
+ const inFlight = inFlightTurnId !== undefined && state !== undefined && !state.ended && inFlightTurnId === state.turnId;
1883
+ if (terminalTurnIds.has(requested)) {
1884
+ replyOk(req.id, { noop: true, turnId: requested });
1885
+ return;
1886
+ }
1887
+ if (inFlight && requested === state.turnId) {
1888
+ if (state.abortRequested) {
1889
+ replyOk(req.id, { noop: true, turnId: state.turnId });
1890
+ return;
1891
+ }
1892
+ const agent = binding?.handle.agent;
1893
+ if (agent === undefined || typeof agent.cancel !== "function") {
1894
+ replyError(req.id, "INTERNAL", "open agent has no cancel() seam");
1895
+ return;
1896
+ }
1897
+ state.abortRequested = true;
1898
+ try {
1899
+ agent.cancel({ kind: "user" }, { keepInbox: true });
1900
+ logger.info("[dsh-opentui-bridge] turn.abort issued turnId=%s sessionId=%s", state.turnId, state.sessionId);
1901
+ replyOk(req.id, { turnId: state.turnId, aborted: true });
1902
+ } catch (err) {
1903
+ state.abortRequested = false;
1904
+ logger.error("[dsh-opentui-bridge] turn.abort failed: %s", err);
1905
+ replyError(req.id, "INTERNAL", err instanceof Error ? err.message : String(err));
1906
+ }
1907
+ return;
1908
+ }
1909
+ replyError(req.id, "TURN_NOT_FOUND", inFlight ? "requested turnId does not match the in-flight turn" : "requested turnId is not a known turn", { requestedTurnId: requested, activeTurnId: inFlightTurnId ?? null });
1910
+ }
1911
+ function handleAskResponse(req) {
1912
+ const parsed = validateAskResponse(req.params);
1913
+ if (!parsed.ok) {
1914
+ replyError(req.id, parsed.code, parsed.message);
1915
+ return;
1916
+ }
1917
+ const pending = pendingAnswerers.get(parsed.value.eventId);
1918
+ if (pending !== undefined)
1919
+ pending.params = parsed.value;
1920
+ const result = ask.answer(binding?.sessionId ?? "", parsed.value);
1921
+ if (!result.ok) {
1922
+ replyError(req.id, result.code, result.message);
1923
+ return;
1924
+ }
1925
+ const settlement = result.settlement;
1926
+ replyOk(req.id, {
1927
+ eventId: settlement.eventId,
1928
+ outcome: settlement.outcome,
1929
+ ...settlement.code !== undefined ? { code: settlement.code } : {},
1930
+ ...settlement.message !== undefined ? { message: settlement.message } : {}
1931
+ });
1932
+ }
1933
+ async function handleListSessions(req) {
1934
+ const controller = resolveSessionController(ctx);
1935
+ if (controller === undefined) {
1936
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.list capability not present", {
1937
+ capability: "session.list",
1938
+ service: "sessionController"
1939
+ });
1940
+ return;
1941
+ }
1942
+ const cursor = req.params.cursor;
1943
+ if (cursor !== undefined && typeof cursor !== "string") {
1944
+ replyError(req.id, "BAD_PARAMS", "session.list cursor must be a string");
1945
+ return;
1946
+ }
1947
+ try {
1948
+ const raw = await controller.list({ _request: cursor !== undefined ? { cursor } : {} });
1949
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw) || !Array.isArray(raw.items)) {
1950
+ const reason = raw === null ? "sessionController.list returned null" : Array.isArray(raw) ? "sessionController.list returned an array, expected a SessionListValue object" : typeof raw !== "object" ? `sessionController.list returned a non-object (${typeof raw})` : "sessionController.list returned an object without an items array";
1951
+ logger.error("[dsh-opentui-bridge] session.list malformed reply: %s", reason);
1952
+ replyError(req.id, "INTERNAL", "sessionController.list returned a malformed value", { reason });
1953
+ return;
1954
+ }
1955
+ const items = raw.items;
1956
+ logger.info("[dsh-opentui-bridge] session.list ok items=%d", items.length);
1957
+ replyOk(req.id, { items });
1958
+ } catch (err) {
1959
+ logger.error("[dsh-opentui-bridge] session.list failed: %s", err);
1960
+ const mapped = mapHostError(err);
1961
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
1962
+ }
1963
+ }
1964
+ async function handleReplay(req) {
1965
+ const persistence = resolvePersistence(ctx);
1966
+ if (persistence === undefined) {
1967
+ replyError(req.id, "INTERNAL", "sessionPersistence service unavailable");
1968
+ return;
1969
+ }
1970
+ const rawId = req.params.sessionId ?? binding?.sessionId;
1971
+ if (typeof rawId !== "string" || rawId === "") {
1972
+ replyError(req.id, "BAD_PARAMS", "journal.replay requires a sessionId (no session is open)");
1973
+ return;
1974
+ }
1975
+ const from = req.params.from;
1976
+ if (from !== undefined && (typeof from !== "number" || !Number.isInteger(from) || from < 0)) {
1977
+ replyError(req.id, "BAD_PARAMS", "journal.replay from must be a non-negative integer seq");
1978
+ return;
1979
+ }
1980
+ const sessionId = rawId;
1981
+ try {
1982
+ const handle = await persistence.open(sessionId, "read");
1983
+ try {
1984
+ const events = [];
1985
+ let offset = 0;
1986
+ for (;; ) {
1987
+ const batch = await handle.read(offset);
1988
+ const slice = batch.events ?? [];
1989
+ if (slice.length === 0)
1990
+ break;
1991
+ events.push(...slice);
1992
+ offset += slice.length;
1993
+ }
1994
+ let maxSeq = -1;
1995
+ const rows = [];
1996
+ for (const e of events) {
1997
+ if (typeof e.seq !== "number" || !Number.isFinite(e.seq)) {
1998
+ throw { name: "SessionPersistenceCorruptionError", message: "journal event has no numeric seq" };
1999
+ }
2000
+ if (e.seq > maxSeq)
2001
+ maxSeq = e.seq;
2002
+ if (from !== undefined && e.seq < from)
2003
+ continue;
2004
+ rows.push({
2005
+ seq: e.seq,
2006
+ type: typeof e.type === "string" ? e.type : "",
2007
+ payload: e.data !== undefined ? e.data : {}
2008
+ });
2009
+ }
2010
+ const cursor = maxSeq + 1;
2011
+ logger.info("[dsh-opentui-bridge] journal.replay ok sessionId=%s rows=%d cursor=%d", sessionId, rows.length, cursor);
2012
+ replyOk(req.id, { rows, cursor });
2013
+ } finally {
2014
+ await handle.close();
2015
+ }
2016
+ } catch (err) {
2017
+ logger.error("[dsh-opentui-bridge] journal.replay failed: %s", err);
2018
+ const mapped = mapHostError(err);
2019
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
2020
+ }
2021
+ }
2022
+ async function handleLine(raw) {
2023
+ let req;
2024
+ try {
2025
+ req = parseRequest(raw);
2026
+ } catch (err) {
2027
+ const e = err;
2028
+ replyError(e.id ?? null, e.code ?? "BAD_FRAME", e.message ?? "malformed frame");
2029
+ return;
2030
+ }
2031
+ if (req.method === "bridge.ping") {
2032
+ replyOk(req.id, { protocolVersion: PROTOCOL_VERSION, bridgeVersion, hostVersion });
2033
+ return;
2034
+ }
2035
+ if (req.method === "bridge.hello") {
2036
+ const clientVersion = req.params.protocolVersion;
2037
+ if (clientVersion !== undefined && clientVersion !== PROTOCOL_VERSION) {
2038
+ replyError(req.id, "VERSION_INCOMPATIBLE", `protocolVersion incompatible: client=${String(clientVersion)}, bridge=${PROTOCOL_VERSION}, host=${hostVersion}`, { clientProtocolVersion: clientVersion, bridgeProtocolVersion: PROTOCOL_VERSION, hostVersion });
2039
+ return;
2040
+ }
2041
+ replyOk(req.id, { protocolVersion: PROTOCOL_VERSION, bridgeVersion, hostVersion });
2042
+ return;
2043
+ }
2044
+ if (req.method === "model.currentSelection") {
2045
+ const defaults = resolveDefaultModel(ctx);
2046
+ if (defaults === undefined) {
2047
+ replyError(req.id, "UNSUPPORTED", "agentDefaultModel service unavailable");
2048
+ return;
2049
+ }
2050
+ try {
2051
+ replyOk(req.id, defaults.currentSelection());
2052
+ } catch (err) {
2053
+ replyError(req.id, "INTERNAL", err instanceof Error ? err.message : String(err));
2054
+ }
2055
+ return;
2056
+ }
2057
+ if (req.method === "session.list") {
2058
+ await handleListSessions(req);
2059
+ return;
2060
+ }
2061
+ if (req.method === "session.open") {
2062
+ await handleOpen(req);
2063
+ return;
2064
+ }
2065
+ if (req.method === "session.send") {
2066
+ await handleSend(req);
2067
+ return;
2068
+ }
2069
+ if (req.method === "session.close") {
2070
+ await handleClose(req);
2071
+ return;
2072
+ }
2073
+ if (req.method === "turn.abort") {
2074
+ handleAbort(req);
2075
+ return;
2076
+ }
2077
+ if (req.method === "ask.response") {
2078
+ handleAskResponse(req);
2079
+ return;
2080
+ }
2081
+ if (req.method === "journal.replay") {
2082
+ await handleReplay(req);
2083
+ return;
2084
+ }
2085
+ replyError(req.id, "UNSUPPORTED", `unsupported method: ${req.method}`);
2086
+ }
2087
+ function enqueueLine(raw) {
2088
+ dispatchChain = dispatchChain.then(() => handleLine(raw)).catch((err) => {
2089
+ logger.error("[dsh-opentui-bridge] unhandled request error: %s", err);
2090
+ });
2091
+ }
2092
+ function onData(chunk) {
2093
+ buffer += chunk;
2094
+ let nl;
2095
+ while ((nl = buffer.indexOf(`
2096
+ `)) !== -1) {
2097
+ const line = buffer.slice(0, nl);
2098
+ buffer = buffer.slice(nl + 1);
2099
+ enqueueLine(line);
2100
+ }
2101
+ }
2102
+ function teardown() {
2103
+ if (closing)
2104
+ return;
2105
+ closing = true;
2106
+ process.stdin.off("data", onData);
2107
+ process.stdin.off("end", onEnd);
2108
+ process.stdin.off("close", onEnd);
2109
+ try {
2110
+ process.stdin.pause();
2111
+ } catch {}
2112
+ clearTurnSubscriptions();
2113
+ for (const eventId of [...pendingAnswerers.keys()]) {
2114
+ settleAnswerer(eventId, { outcome: "cancelled" });
2115
+ }
2116
+ try {
2117
+ unsubApprovalAnswerer?.();
2118
+ } catch {}
2119
+ try {
2120
+ unsubQuestionsAnswerer?.();
2121
+ } catch {}
2122
+ unsubApprovalAnswerer = undefined;
2123
+ unsubQuestionsAnswerer = undefined;
2124
+ ask.dispose();
2125
+ logger.info("[dsh-opentui-bridge] stdio protocol disposed");
2126
+ }
2127
+ let exitRequested = false;
2128
+ function requestGracefulExit() {
2129
+ if (exitRequested)
2130
+ return;
2131
+ exitRequested = true;
2132
+ const finish = () => {
2133
+ const resolved = resolveAppExit(ctx);
2134
+ if (resolved === undefined) {
2135
+ logger.warn("[dsh-opentui-bridge] appExit service unavailable (host version difference); falling back to process.exitCode=0 and allowing natural exit");
2136
+ process.exitCode = 0;
2137
+ return;
2138
+ }
2139
+ logger.info(`[dsh-opentui-bridge] requesting appExit(0) via ${resolved.source} for graceful host shutdown`);
2140
+ try {
2141
+ resolved.fn(0);
2142
+ } catch (err) {
2143
+ logger.error("[dsh-opentui-bridge] appExit(0) threw; leaving exit to the host: %s", err);
2144
+ }
2145
+ };
2146
+ if (process.stdout.writableLength > 0) {
2147
+ let done = false;
2148
+ const once = () => {
2149
+ if (done)
2150
+ return;
2151
+ done = true;
2152
+ finish();
2153
+ };
2154
+ process.stdout.once("drain", once);
2155
+ const timer = setTimeout(once, 200);
2156
+ timer.unref();
2157
+ } else {
2158
+ finish();
2159
+ }
2160
+ }
2161
+ function onEnd() {
2162
+ if (eofSeen)
2163
+ return;
2164
+ eofSeen = true;
2165
+ if (buffer.trim())
2166
+ enqueueLine(buffer);
2167
+ buffer = "";
2168
+ dispatchChain.finally(() => {
2169
+ teardown();
2170
+ requestGracefulExit();
2171
+ });
2172
+ }
2173
+ armTurnSubscriptions();
2174
+ armAskAnswerers();
2175
+ process.stdin.setEncoding("utf8");
2176
+ process.stdin.on("data", onData);
2177
+ process.stdin.on("end", onEnd);
2178
+ process.stdin.on("close", onEnd);
2179
+ return ctx.effect(() => () => {
2180
+ teardown();
2181
+ logger.info("[dsh-opentui-bridge] host graceful shutdown: fiber disposed");
2182
+ }, "dsh-opentui-bridge: stdio");
2183
+ }
2184
+ export {
2185
+ ASK_ERROR_CODES,
2186
+ ASK_FRAME_TYPES,
2187
+ ASK_GRANT_JOURNAL_TYPE,
2188
+ ASK_JOURNAL_KINDS,
2189
+ ASK_PLUGIN_RECORD_PREFIX,
2190
+ AskRegistry,
2191
+ SessionPermissionSummary,
2192
+ alwaysGrantToolsFromJournal,
2193
+ apply,
2194
+ armAppendSection,
2195
+ askPluginRecordType,
2196
+ askRegistry,
2197
+ createAskRegistry,
2198
+ getAskRegistry,
2199
+ inject,
2200
+ isAskErrorCode,
2201
+ name,
2202
+ redactIdentifier,
2203
+ summarizeAnswers,
2204
+ turnIdOf,
2205
+ validateAskCancel,
2206
+ validateAskEvent,
2207
+ validateAskPending,
2208
+ validateAskRequest,
2209
+ validateAskResponse,
2210
+ validateAskSettled
2211
+ };