dsh-hello 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +508 -2
- package/cordis.patch.yml +3 -0
- package/lib/catalogs.d.ts +100 -0
- package/lib/catalogs.d.ts.map +1 -0
- package/lib/catalogs.js +205 -0
- package/lib/catalogs.js.map +1 -0
- package/lib/client.js +544 -0
- package/lib/config.d.ts +96 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +110 -0
- package/lib/config.js.map +1 -0
- package/lib/devices.d.ts +71 -0
- package/lib/devices.d.ts.map +1 -0
- package/lib/devices.js +219 -0
- package/lib/devices.js.map +1 -0
- package/lib/files.d.ts +43 -0
- package/lib/files.d.ts.map +1 -0
- package/lib/files.js +187 -0
- package/lib/files.js.map +1 -0
- package/lib/host.d.ts +324 -0
- package/lib/host.d.ts.map +1 -0
- package/lib/host.js +10 -0
- package/lib/host.js.map +1 -0
- package/lib/http.d.ts +77 -0
- package/lib/http.d.ts.map +1 -0
- package/lib/http.js +340 -0
- package/lib/http.js.map +1 -0
- package/lib/index.d.ts +20 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +8227 -0
- package/lib/index.js.map +7 -0
- package/lib/interactions.d.ts +99 -0
- package/lib/interactions.d.ts.map +1 -0
- package/lib/interactions.js +568 -0
- package/lib/interactions.js.map +1 -0
- package/lib/pairing.d.ts +56 -0
- package/lib/pairing.d.ts.map +1 -0
- package/lib/pairing.js +128 -0
- package/lib/pairing.js.map +1 -0
- package/lib/protocol.d.ts +336 -0
- package/lib/protocol.d.ts.map +1 -0
- package/lib/protocol.js +7 -0
- package/lib/protocol.js.map +1 -0
- package/lib/push.d.ts +47 -0
- package/lib/push.d.ts.map +1 -0
- package/lib/push.js +339 -0
- package/lib/push.js.map +1 -0
- package/lib/read-state.d.ts +32 -0
- package/lib/read-state.d.ts.map +1 -0
- package/lib/read-state.js +39 -0
- package/lib/read-state.js.map +1 -0
- package/lib/routes.d.ts +33 -0
- package/lib/routes.d.ts.map +1 -0
- package/lib/routes.js +1293 -0
- package/lib/routes.js.map +1 -0
- package/lib/schedules.d.ts +31 -0
- package/lib/schedules.d.ts.map +1 -0
- package/lib/schedules.js +122 -0
- package/lib/schedules.js.map +1 -0
- package/lib/sessions.d.ts +60 -0
- package/lib/sessions.d.ts.map +1 -0
- package/lib/sessions.js +287 -0
- package/lib/sessions.js.map +1 -0
- package/lib/speech.d.ts +20 -0
- package/lib/speech.d.ts.map +1 -0
- package/lib/speech.js +47 -0
- package/lib/speech.js.map +1 -0
- package/lib/streams.d.ts +30 -0
- package/lib/streams.d.ts.map +1 -0
- package/lib/streams.js +106 -0
- package/lib/streams.js.map +1 -0
- package/lib/terminal.d.ts +55 -0
- package/lib/terminal.d.ts.map +1 -0
- package/lib/terminal.js +231 -0
- package/lib/terminal.js.map +1 -0
- package/lib/util.d.ts +18 -0
- package/lib/util.d.ts.map +1 -0
- package/lib/util.js +52 -0
- package/lib/util.js.map +1 -0
- package/lib/version.d.ts +15 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +98 -0
- package/lib/version.js.map +1 -0
- package/package.json +80 -4
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { Config } from './config.js';
|
|
2
|
+
import type { HostContext } from './host.js';
|
|
3
|
+
import type { ApprovalItem, ApprovalDecision, ApprovalPreview, QuestionItem, QuestionItemEnvelope } from './protocol.js';
|
|
4
|
+
import type { SseHub } from './streams.js';
|
|
5
|
+
export interface QuestionAnswer {
|
|
6
|
+
answers: Array<{
|
|
7
|
+
id: string;
|
|
8
|
+
selected: string[];
|
|
9
|
+
custom?: string;
|
|
10
|
+
}>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Owns the human-interaction seams. The policy is:
|
|
14
|
+
*
|
|
15
|
+
* - a foreground app with a live SSE connection answers first, so the plugin
|
|
16
|
+
* claims the request even while a browser is connected;
|
|
17
|
+
* - otherwise a live browser Client answers first and the plugin calls `next()`;
|
|
18
|
+
* - with neither, the request is pushed to the app and held until it answers or
|
|
19
|
+
* the configured timeout elapses;
|
|
20
|
+
* - timeout, cancellation and an app leaving the foreground fall back to
|
|
21
|
+
* `next()`, restoring dsh's own fail-closed behavior instead of inventing an
|
|
22
|
+
* outcome.
|
|
23
|
+
*/
|
|
24
|
+
export declare class InteractionBroker {
|
|
25
|
+
private readonly ctx;
|
|
26
|
+
private readonly config;
|
|
27
|
+
private readonly hub;
|
|
28
|
+
private readonly push;
|
|
29
|
+
private readonly logger;
|
|
30
|
+
private readonly approvals;
|
|
31
|
+
private readonly questions;
|
|
32
|
+
private readonly grants;
|
|
33
|
+
/** Last foreground heartbeat per paired device. */
|
|
34
|
+
private readonly foreground;
|
|
35
|
+
/** Hands held interactions back if a foreground app dies without a false ping. */
|
|
36
|
+
private readonly presenceSweep;
|
|
37
|
+
constructor(ctx: HostContext, config: Config, hub: SseHub, push: {
|
|
38
|
+
isConfigured(): boolean;
|
|
39
|
+
notify(kind: 'approval' | 'question', payload: unknown): void;
|
|
40
|
+
}, logger: {
|
|
41
|
+
info(message: string): void;
|
|
42
|
+
warn(message: string): void;
|
|
43
|
+
});
|
|
44
|
+
register(): void;
|
|
45
|
+
listApprovals(): ApprovalItem[];
|
|
46
|
+
/**
|
|
47
|
+
* Record whether one paired device is in the foreground. A foreground device
|
|
48
|
+
* with a live SSE connection takes priority over a connected browser; leaving
|
|
49
|
+
* the foreground immediately hands its held questions/approvals back to dsh.
|
|
50
|
+
*/
|
|
51
|
+
setPresence(deviceId: string, foreground: boolean): void;
|
|
52
|
+
/** Create a synthetic approval for the authenticated debug route. */
|
|
53
|
+
createDebugApproval(input: {
|
|
54
|
+
sessionId?: string;
|
|
55
|
+
toolName?: string;
|
|
56
|
+
reason?: string;
|
|
57
|
+
displayReason?: {
|
|
58
|
+
en: string;
|
|
59
|
+
[locale: string]: string;
|
|
60
|
+
};
|
|
61
|
+
}): ApprovalItem;
|
|
62
|
+
/** Create a synthetic question for the authenticated debug route. */
|
|
63
|
+
createDebugQuestion(input: {
|
|
64
|
+
sessionId?: string;
|
|
65
|
+
questions?: QuestionItem[];
|
|
66
|
+
}): QuestionItemEnvelope;
|
|
67
|
+
listQuestions(): QuestionItemEnvelope[];
|
|
68
|
+
decideApproval(id: string, decision: ApprovalDecision): ApprovalItem | undefined;
|
|
69
|
+
answerQuestion(id: string, answer: QuestionAnswer): QuestionItemEnvelope | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Answer a question that outlived its foreground wait. dsh records the
|
|
72
|
+
* answer as a `user-question-reply` steered into the agent; the projection
|
|
73
|
+
* then closes the call.
|
|
74
|
+
*/
|
|
75
|
+
answerContinued(sessionId: string, callId: string, answer: QuestionAnswer): Promise<boolean>;
|
|
76
|
+
hasGrant(sessionId: string, toolName: string): boolean;
|
|
77
|
+
private handleApproval;
|
|
78
|
+
private handleQuestion;
|
|
79
|
+
/**
|
|
80
|
+
* Read the approval's `tool/call` event and produce a small presentation
|
|
81
|
+
* preview. This is best-effort: a missing/old page must never delay or block
|
|
82
|
+
* the approval itself.
|
|
83
|
+
*/
|
|
84
|
+
private buildApprovalPreview;
|
|
85
|
+
private browserWins;
|
|
86
|
+
/** A foreground app only wins while its SSE connection can receive the card. */
|
|
87
|
+
private phoneWins;
|
|
88
|
+
private hasForegroundPhone;
|
|
89
|
+
/**
|
|
90
|
+
* The app left the foreground (or stopped heartbeating). Any interaction it
|
|
91
|
+
* was holding goes back to dsh so a connected browser can render it now.
|
|
92
|
+
*/
|
|
93
|
+
private releasePhoneHolds;
|
|
94
|
+
private appCanAnswer;
|
|
95
|
+
dispose(): void;
|
|
96
|
+
logFailure(error: unknown): void;
|
|
97
|
+
}
|
|
98
|
+
export declare function previewToolCall(toolName: string, value: unknown): ApprovalPreview | undefined;
|
|
99
|
+
//# sourceMappingURL=interactions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interactions.d.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AIjB,OAAO,CAAC,kBAAkB;IAQ1B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IA6BzB,OAAO,CAAC,YAAY;IAIpB,OAAO,IAAI,IAAI;IAef,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;CAGjC;AAgBD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,eAAe,GAAG,SAAS,CAqE7F"}
|
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
import { newId, shortError } from './util.js';
|
|
2
|
+
/** A foreground claim expires if the app stops heartbeating (killed, frozen). */
|
|
3
|
+
const PRESENCE_TTL_MS = 45_000;
|
|
4
|
+
/**
|
|
5
|
+
* Owns the human-interaction seams. The policy is:
|
|
6
|
+
*
|
|
7
|
+
* - a foreground app with a live SSE connection answers first, so the plugin
|
|
8
|
+
* claims the request even while a browser is connected;
|
|
9
|
+
* - otherwise a live browser Client answers first and the plugin calls `next()`;
|
|
10
|
+
* - with neither, the request is pushed to the app and held until it answers or
|
|
11
|
+
* the configured timeout elapses;
|
|
12
|
+
* - timeout, cancellation and an app leaving the foreground fall back to
|
|
13
|
+
* `next()`, restoring dsh's own fail-closed behavior instead of inventing an
|
|
14
|
+
* outcome.
|
|
15
|
+
*/
|
|
16
|
+
export class InteractionBroker {
|
|
17
|
+
ctx;
|
|
18
|
+
config;
|
|
19
|
+
hub;
|
|
20
|
+
push;
|
|
21
|
+
logger;
|
|
22
|
+
approvals = new Map();
|
|
23
|
+
questions = new Map();
|
|
24
|
+
grants = new Set();
|
|
25
|
+
/** Last foreground heartbeat per paired device. */
|
|
26
|
+
foreground = new Map();
|
|
27
|
+
/** Hands held interactions back if a foreground app dies without a false ping. */
|
|
28
|
+
presenceSweep = setInterval(() => this.releasePhoneHolds(), 15_000);
|
|
29
|
+
constructor(ctx, config, hub, push, logger) {
|
|
30
|
+
this.ctx = ctx;
|
|
31
|
+
this.config = config;
|
|
32
|
+
this.hub = hub;
|
|
33
|
+
this.push = push;
|
|
34
|
+
this.logger = logger;
|
|
35
|
+
}
|
|
36
|
+
register() {
|
|
37
|
+
this.presenceSweep.unref?.();
|
|
38
|
+
this.ctx.on('approval/request', async (...args) => {
|
|
39
|
+
const req = args[0];
|
|
40
|
+
const next = args[1];
|
|
41
|
+
return this.handleApproval(req, next);
|
|
42
|
+
});
|
|
43
|
+
this.ctx.on('user-questions/request', async (...args) => {
|
|
44
|
+
const req = args[0];
|
|
45
|
+
const next = args[1];
|
|
46
|
+
return this.handleQuestion(req, next);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
listApprovals() {
|
|
50
|
+
return [...this.approvals.values()].map(toApprovalItem);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Record whether one paired device is in the foreground. A foreground device
|
|
54
|
+
* with a live SSE connection takes priority over a connected browser; leaving
|
|
55
|
+
* the foreground immediately hands its held questions/approvals back to dsh.
|
|
56
|
+
*/
|
|
57
|
+
setPresence(deviceId, foreground) {
|
|
58
|
+
const before = this.hasForegroundPhone();
|
|
59
|
+
if (foreground)
|
|
60
|
+
this.foreground.set(deviceId, Date.now());
|
|
61
|
+
else
|
|
62
|
+
this.foreground.delete(deviceId);
|
|
63
|
+
const after = this.hasForegroundPhone();
|
|
64
|
+
if (before !== after)
|
|
65
|
+
this.logger.info(`[dsh-door] foreground app ${after ? 'claims' : 'releases'} interactions`);
|
|
66
|
+
this.releasePhoneHolds();
|
|
67
|
+
}
|
|
68
|
+
/** Create a synthetic approval for the authenticated debug route. */
|
|
69
|
+
createDebugApproval(input) {
|
|
70
|
+
const id = newId();
|
|
71
|
+
const createdAt = Date.now();
|
|
72
|
+
const expiresAt = createdAt + this.config.approvalWaitTimeoutMs;
|
|
73
|
+
const timer = setTimeout(() => {
|
|
74
|
+
this.approvals.delete(id);
|
|
75
|
+
this.hub.broadcast('approval-resolved', { id, decision: 'timeout', source: 'timeout' });
|
|
76
|
+
}, this.config.approvalWaitTimeoutMs);
|
|
77
|
+
timer.unref?.();
|
|
78
|
+
const pending = {
|
|
79
|
+
id,
|
|
80
|
+
sessionId: input.sessionId ?? 'debug-session',
|
|
81
|
+
toolName: input.toolName ?? 'bash',
|
|
82
|
+
reason: input.reason ?? 'Debug approval from the mobile app',
|
|
83
|
+
displayReason: input.displayReason ?? { en: 'Run a command', zh: '执行一条命令' },
|
|
84
|
+
createdAt,
|
|
85
|
+
expiresAt,
|
|
86
|
+
phoneHold: false,
|
|
87
|
+
resolve: () => undefined,
|
|
88
|
+
timer,
|
|
89
|
+
};
|
|
90
|
+
this.approvals.set(id, pending);
|
|
91
|
+
this.hub.broadcast('approval', toApprovalItem(pending));
|
|
92
|
+
return toApprovalItem(pending);
|
|
93
|
+
}
|
|
94
|
+
/** Create a synthetic question for the authenticated debug route. */
|
|
95
|
+
createDebugQuestion(input) {
|
|
96
|
+
const id = newId();
|
|
97
|
+
const createdAt = Date.now();
|
|
98
|
+
const expiresAt = createdAt + this.config.questionWaitTimeoutMs;
|
|
99
|
+
const questions = input.questions ?? [{
|
|
100
|
+
id: 'debug-choice',
|
|
101
|
+
header: '调试问题',
|
|
102
|
+
question: '这条消息只用于验证手机端的提问卡片,选一个即可。',
|
|
103
|
+
options: [{ label: '继续' }, { label: '取消' }],
|
|
104
|
+
}];
|
|
105
|
+
const timer = setTimeout(() => {
|
|
106
|
+
this.questions.delete(id);
|
|
107
|
+
this.hub.broadcast('question-resolved', { id, decision: 'timeout', source: 'timeout' });
|
|
108
|
+
}, this.config.questionWaitTimeoutMs);
|
|
109
|
+
timer.unref?.();
|
|
110
|
+
const pending = {
|
|
111
|
+
id,
|
|
112
|
+
sessionId: input.sessionId ?? 'debug-session',
|
|
113
|
+
questions,
|
|
114
|
+
createdAt,
|
|
115
|
+
expiresAt,
|
|
116
|
+
phoneHold: false,
|
|
117
|
+
resolve: () => undefined,
|
|
118
|
+
timer,
|
|
119
|
+
};
|
|
120
|
+
this.questions.set(id, pending);
|
|
121
|
+
const envelope = {
|
|
122
|
+
id,
|
|
123
|
+
sessionId: pending.sessionId,
|
|
124
|
+
questions,
|
|
125
|
+
createdAt,
|
|
126
|
+
expiresAt,
|
|
127
|
+
};
|
|
128
|
+
this.hub.broadcast('question', envelope);
|
|
129
|
+
return envelope;
|
|
130
|
+
}
|
|
131
|
+
listQuestions() {
|
|
132
|
+
return [...this.questions.values()].map(item => ({
|
|
133
|
+
id: item.id,
|
|
134
|
+
sessionId: item.sessionId,
|
|
135
|
+
callId: item.callId,
|
|
136
|
+
questions: item.questions,
|
|
137
|
+
createdAt: item.createdAt,
|
|
138
|
+
expiresAt: item.expiresAt,
|
|
139
|
+
}));
|
|
140
|
+
}
|
|
141
|
+
decideApproval(id, decision) {
|
|
142
|
+
const pending = this.approvals.get(id);
|
|
143
|
+
if (pending === undefined)
|
|
144
|
+
return undefined;
|
|
145
|
+
clearTimeout(pending.timer);
|
|
146
|
+
this.approvals.delete(id);
|
|
147
|
+
if (decision === 'always' && this.config.allowSessionWideGrants) {
|
|
148
|
+
this.grants.add(grantKey(pending.sessionId, pending.toolName));
|
|
149
|
+
}
|
|
150
|
+
pending.resolve(decision);
|
|
151
|
+
this.hub.broadcast('approval-resolved', {
|
|
152
|
+
id,
|
|
153
|
+
sessionId: pending.sessionId,
|
|
154
|
+
decision,
|
|
155
|
+
source: 'app',
|
|
156
|
+
});
|
|
157
|
+
return toApprovalItem(pending);
|
|
158
|
+
}
|
|
159
|
+
answerQuestion(id, answer) {
|
|
160
|
+
const pending = this.questions.get(id);
|
|
161
|
+
if (pending === undefined)
|
|
162
|
+
return undefined;
|
|
163
|
+
clearTimeout(pending.timer);
|
|
164
|
+
this.questions.delete(id);
|
|
165
|
+
pending.resolve(answer);
|
|
166
|
+
this.hub.broadcast('question-resolved', {
|
|
167
|
+
id,
|
|
168
|
+
sessionId: pending.sessionId,
|
|
169
|
+
callId: pending.callId,
|
|
170
|
+
source: 'app',
|
|
171
|
+
});
|
|
172
|
+
return {
|
|
173
|
+
id: pending.id,
|
|
174
|
+
sessionId: pending.sessionId,
|
|
175
|
+
callId: pending.callId,
|
|
176
|
+
questions: pending.questions,
|
|
177
|
+
createdAt: pending.createdAt,
|
|
178
|
+
expiresAt: pending.expiresAt,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Answer a question that outlived its foreground wait. dsh records the
|
|
183
|
+
* answer as a `user-question-reply` steered into the agent; the projection
|
|
184
|
+
* then closes the call.
|
|
185
|
+
*/
|
|
186
|
+
async answerContinued(sessionId, callId, answer) {
|
|
187
|
+
const questions = getService(this.ctx, 'userQuestions');
|
|
188
|
+
const controller = this.ctx.sessionController;
|
|
189
|
+
if (questions === undefined || controller === undefined)
|
|
190
|
+
return false;
|
|
191
|
+
const resolved = await controller.resolveAgent(sessionId);
|
|
192
|
+
const agent = resolved.agent;
|
|
193
|
+
if (agent === undefined)
|
|
194
|
+
throw new Error(resolved.error?.message ?? 'session is not available');
|
|
195
|
+
return questions.answer(agent, callId, answer);
|
|
196
|
+
}
|
|
197
|
+
hasGrant(sessionId, toolName) {
|
|
198
|
+
return this.grants.has(grantKey(sessionId, toolName));
|
|
199
|
+
}
|
|
200
|
+
async handleApproval(req, next) {
|
|
201
|
+
const sessionId = req.agent?.id ?? 'unknown';
|
|
202
|
+
if (this.hasGrant(sessionId, req.toolName)) {
|
|
203
|
+
this.hub.broadcast('approval-resolved', {
|
|
204
|
+
id: `grant:${newId()}`,
|
|
205
|
+
sessionId,
|
|
206
|
+
toolName: req.toolName,
|
|
207
|
+
decision: 'always',
|
|
208
|
+
source: 'grant',
|
|
209
|
+
});
|
|
210
|
+
return 'allowed-once';
|
|
211
|
+
}
|
|
212
|
+
const phoneHold = this.phoneWins();
|
|
213
|
+
if (!phoneHold && this.browserWins())
|
|
214
|
+
return next();
|
|
215
|
+
if (!this.appCanAnswer()) {
|
|
216
|
+
// Nothing can answer: keep dsh's fail-closed path instead of holding a
|
|
217
|
+
// turn for two minutes for an app that is not connected.
|
|
218
|
+
return next();
|
|
219
|
+
}
|
|
220
|
+
if (req.signal?.aborted === true)
|
|
221
|
+
return 'cancelled';
|
|
222
|
+
const id = newId();
|
|
223
|
+
const createdAt = Date.now();
|
|
224
|
+
const expiresAt = createdAt + this.config.approvalWaitTimeoutMs;
|
|
225
|
+
const preview = await this.buildApprovalPreview(sessionId, req);
|
|
226
|
+
const decision = await new Promise((resolve) => {
|
|
227
|
+
const timer = setTimeout(() => {
|
|
228
|
+
this.approvals.delete(id);
|
|
229
|
+
this.hub.broadcast('approval-resolved', { id, sessionId, decision: 'timeout', source: 'timeout' });
|
|
230
|
+
resolve('timeout');
|
|
231
|
+
}, this.config.approvalWaitTimeoutMs);
|
|
232
|
+
timer.unref?.();
|
|
233
|
+
const pending = {
|
|
234
|
+
id,
|
|
235
|
+
sessionId,
|
|
236
|
+
toolName: req.toolName,
|
|
237
|
+
callId: req.callId,
|
|
238
|
+
reason: req.reason,
|
|
239
|
+
displayReason: req.displayReason,
|
|
240
|
+
...(preview === undefined ? {} : { preview }),
|
|
241
|
+
createdAt,
|
|
242
|
+
expiresAt,
|
|
243
|
+
phoneHold,
|
|
244
|
+
resolve,
|
|
245
|
+
timer,
|
|
246
|
+
};
|
|
247
|
+
this.approvals.set(id, pending);
|
|
248
|
+
this.hub.broadcast('approval', toApprovalItem(pending));
|
|
249
|
+
this.push.notify('approval', toApprovalItem(pending));
|
|
250
|
+
req.signal?.addEventListener('abort', () => {
|
|
251
|
+
if (!this.approvals.has(id))
|
|
252
|
+
return;
|
|
253
|
+
clearTimeout(timer);
|
|
254
|
+
this.approvals.delete(id);
|
|
255
|
+
this.hub.broadcast('approval-resolved', { id, sessionId, decision: 'cancelled', source: 'signal' });
|
|
256
|
+
resolve('timeout');
|
|
257
|
+
}, { once: true });
|
|
258
|
+
this.logger.info(`[dsh-door] approval ${id} for ${req.toolName} in ${sessionId}`);
|
|
259
|
+
});
|
|
260
|
+
if (decision === 'timeout') {
|
|
261
|
+
// Delegate to the next listener; with no browser this becomes dsh's
|
|
262
|
+
// fail-closed `unavailable`.
|
|
263
|
+
return next();
|
|
264
|
+
}
|
|
265
|
+
if (decision === 'deny')
|
|
266
|
+
return 'rejected';
|
|
267
|
+
return 'allowed-once';
|
|
268
|
+
}
|
|
269
|
+
async handleQuestion(req, next) {
|
|
270
|
+
const sessionId = req.agent?.id ?? 'unknown';
|
|
271
|
+
this.logger.info(`[dsh-door] question request in ${sessionId}: phone=${this.phoneWins()} presence=${this.hasForegroundPhone()} hub=${this.hub.hasClients()} browser=${this.browserWins()}`);
|
|
272
|
+
const phoneHold = this.phoneWins();
|
|
273
|
+
if (!phoneHold && this.browserWins())
|
|
274
|
+
return next();
|
|
275
|
+
if (!this.appCanAnswer())
|
|
276
|
+
return next();
|
|
277
|
+
if (req.signal?.aborted === true)
|
|
278
|
+
return next();
|
|
279
|
+
const id = newId();
|
|
280
|
+
const createdAt = Date.now();
|
|
281
|
+
const expiresAt = createdAt + this.config.questionWaitTimeoutMs;
|
|
282
|
+
const answer = await new Promise((resolve) => {
|
|
283
|
+
const timer = setTimeout(() => {
|
|
284
|
+
this.questions.delete(id);
|
|
285
|
+
this.hub.broadcast('question-resolved', { id, sessionId, callId: req.wait?.callId, decision: 'timeout', source: 'timeout' });
|
|
286
|
+
resolve('timeout');
|
|
287
|
+
}, this.config.questionWaitTimeoutMs);
|
|
288
|
+
timer.unref?.();
|
|
289
|
+
const pending = {
|
|
290
|
+
id,
|
|
291
|
+
sessionId,
|
|
292
|
+
callId: req.wait?.callId,
|
|
293
|
+
questions: req.questions,
|
|
294
|
+
createdAt,
|
|
295
|
+
expiresAt,
|
|
296
|
+
phoneHold,
|
|
297
|
+
resolve,
|
|
298
|
+
timer,
|
|
299
|
+
};
|
|
300
|
+
this.questions.set(id, pending);
|
|
301
|
+
const envelope = {
|
|
302
|
+
id,
|
|
303
|
+
sessionId,
|
|
304
|
+
callId: req.wait?.callId,
|
|
305
|
+
questions: req.questions,
|
|
306
|
+
createdAt,
|
|
307
|
+
expiresAt,
|
|
308
|
+
};
|
|
309
|
+
this.hub.broadcast('question', envelope);
|
|
310
|
+
this.push.notify('question', envelope);
|
|
311
|
+
req.signal?.addEventListener('abort', () => {
|
|
312
|
+
if (!this.questions.has(id))
|
|
313
|
+
return;
|
|
314
|
+
clearTimeout(timer);
|
|
315
|
+
this.questions.delete(id);
|
|
316
|
+
this.hub.broadcast('question-resolved', { id, sessionId, callId: req.wait?.callId, decision: 'cancelled', source: 'signal' });
|
|
317
|
+
resolve('timeout');
|
|
318
|
+
}, { once: true });
|
|
319
|
+
this.logger.info(`[dsh-door] question ${id} in ${sessionId} (${phoneHold ? 'foreground app' : 'app'})`);
|
|
320
|
+
});
|
|
321
|
+
if (answer === 'timeout')
|
|
322
|
+
return next();
|
|
323
|
+
return answer;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Read the approval's `tool/call` event and produce a small presentation
|
|
327
|
+
* preview. This is best-effort: a missing/old page must never delay or block
|
|
328
|
+
* the approval itself.
|
|
329
|
+
*/
|
|
330
|
+
async buildApprovalPreview(sessionId, req) {
|
|
331
|
+
const controller = this.ctx.sessionController;
|
|
332
|
+
if (controller === undefined || req.callId === undefined)
|
|
333
|
+
return undefined;
|
|
334
|
+
const abort = new AbortController();
|
|
335
|
+
const timer = setTimeout(() => abort.abort(), 700);
|
|
336
|
+
timer.unref?.();
|
|
337
|
+
try {
|
|
338
|
+
const page = await controller.page({
|
|
339
|
+
address: { kind: 'session', sessionId: sessionId },
|
|
340
|
+
maxMessages: 120,
|
|
341
|
+
turnWindow: { minMessages: 20, minTurns: 1 },
|
|
342
|
+
}, abort.signal);
|
|
343
|
+
const events = page.records.map(entry => entry.event);
|
|
344
|
+
let call = events.find(event => event.type === 'tool/call'
|
|
345
|
+
&& String(event.data?.callId ?? '') === req.callId);
|
|
346
|
+
if (call === undefined) {
|
|
347
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
348
|
+
const event = events[index];
|
|
349
|
+
if (event.type === 'tool/call'
|
|
350
|
+
&& String(event.data?.name ?? '') === req.toolName) {
|
|
351
|
+
call = event;
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (call === undefined)
|
|
357
|
+
return undefined;
|
|
358
|
+
return previewToolCall(req.toolName, call.data);
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
finally {
|
|
364
|
+
clearTimeout(timer);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
browserWins() {
|
|
368
|
+
const gateway = getService(this.ctx, 'typertGateway');
|
|
369
|
+
return gateway?.hasLiveClient() === true;
|
|
370
|
+
}
|
|
371
|
+
/** A foreground app only wins while its SSE connection can receive the card. */
|
|
372
|
+
phoneWins() {
|
|
373
|
+
return this.hasForegroundPhone() && this.hub.hasClients();
|
|
374
|
+
}
|
|
375
|
+
hasForegroundPhone() {
|
|
376
|
+
const now = Date.now();
|
|
377
|
+
for (const [deviceId, at] of this.foreground) {
|
|
378
|
+
if (now - at > PRESENCE_TTL_MS)
|
|
379
|
+
this.foreground.delete(deviceId);
|
|
380
|
+
}
|
|
381
|
+
return this.foreground.size > 0;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* The app left the foreground (or stopped heartbeating). Any interaction it
|
|
385
|
+
* was holding goes back to dsh so a connected browser can render it now.
|
|
386
|
+
*/
|
|
387
|
+
releasePhoneHolds() {
|
|
388
|
+
if (this.hasForegroundPhone())
|
|
389
|
+
return;
|
|
390
|
+
for (const [id, pending] of [...this.questions]) {
|
|
391
|
+
if (!pending.phoneHold)
|
|
392
|
+
continue;
|
|
393
|
+
clearTimeout(pending.timer);
|
|
394
|
+
this.questions.delete(id);
|
|
395
|
+
this.hub.broadcast('question-resolved', {
|
|
396
|
+
id,
|
|
397
|
+
sessionId: pending.sessionId,
|
|
398
|
+
callId: pending.callId,
|
|
399
|
+
decision: 'delegated',
|
|
400
|
+
source: 'presence',
|
|
401
|
+
});
|
|
402
|
+
pending.resolve('timeout');
|
|
403
|
+
}
|
|
404
|
+
for (const [id, pending] of [...this.approvals]) {
|
|
405
|
+
if (!pending.phoneHold)
|
|
406
|
+
continue;
|
|
407
|
+
clearTimeout(pending.timer);
|
|
408
|
+
this.approvals.delete(id);
|
|
409
|
+
this.hub.broadcast('approval-resolved', {
|
|
410
|
+
id,
|
|
411
|
+
sessionId: pending.sessionId,
|
|
412
|
+
decision: 'delegated',
|
|
413
|
+
source: 'presence',
|
|
414
|
+
});
|
|
415
|
+
pending.resolve('timeout');
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
appCanAnswer() {
|
|
419
|
+
return this.hub.hasClients() || this.push.isConfigured();
|
|
420
|
+
}
|
|
421
|
+
dispose() {
|
|
422
|
+
clearInterval(this.presenceSweep);
|
|
423
|
+
this.foreground.clear();
|
|
424
|
+
for (const pending of this.approvals.values()) {
|
|
425
|
+
clearTimeout(pending.timer);
|
|
426
|
+
pending.resolve('timeout');
|
|
427
|
+
}
|
|
428
|
+
this.approvals.clear();
|
|
429
|
+
for (const pending of this.questions.values()) {
|
|
430
|
+
clearTimeout(pending.timer);
|
|
431
|
+
pending.resolve('timeout');
|
|
432
|
+
}
|
|
433
|
+
this.questions.clear();
|
|
434
|
+
}
|
|
435
|
+
logFailure(error) {
|
|
436
|
+
this.logger.warn(`[dsh-door] interaction failed: ${shortError(error)}`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
function toApprovalItem(pending) {
|
|
440
|
+
return {
|
|
441
|
+
id: pending.id,
|
|
442
|
+
sessionId: pending.sessionId,
|
|
443
|
+
toolName: pending.toolName,
|
|
444
|
+
callId: pending.callId,
|
|
445
|
+
reason: pending.reason,
|
|
446
|
+
displayReason: pending.displayReason,
|
|
447
|
+
...(pending.preview === undefined ? {} : { preview: pending.preview }),
|
|
448
|
+
createdAt: pending.createdAt,
|
|
449
|
+
expiresAt: pending.expiresAt,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
export function previewToolCall(toolName, value) {
|
|
453
|
+
const data = asRecord(value);
|
|
454
|
+
if (data === null)
|
|
455
|
+
return undefined;
|
|
456
|
+
const raw = typeof data.arguments === 'string'
|
|
457
|
+
? data.arguments
|
|
458
|
+
: data.arguments === undefined ? undefined : safeStringify(data.arguments);
|
|
459
|
+
const args = parseArgs(raw);
|
|
460
|
+
const path = firstString(args, ['file_path', 'path', 'file']);
|
|
461
|
+
const command = firstString(args, ['command', 'cmd']);
|
|
462
|
+
if (toolName === 'bash' || toolName === 'pwsh' || toolName === 'shell') {
|
|
463
|
+
if (command === null)
|
|
464
|
+
return undefined;
|
|
465
|
+
return { kind: 'command', title: '执行命令', detail: `$ ${truncate(command, 1200)}` };
|
|
466
|
+
}
|
|
467
|
+
if (toolName === 'edit' || toolName === 'apply_patch' || toolName === 'write') {
|
|
468
|
+
const oldText = firstString(args, ['old_string', 'oldString', 'old_text', 'oldText']);
|
|
469
|
+
const newText = firstString(args, ['new_string', 'newString', 'new_text', 'newText']);
|
|
470
|
+
const patch = firstString(args, ['patch', 'diff']);
|
|
471
|
+
if (oldText !== null && newText !== null) {
|
|
472
|
+
const removed = oldText.length === 0 ? 0 : oldText.split('\n').length;
|
|
473
|
+
const added = newText.length === 0 ? 0 : newText.split('\n').length;
|
|
474
|
+
const detail = [
|
|
475
|
+
path === null ? 'file' : path,
|
|
476
|
+
'--- old',
|
|
477
|
+
...oldText.split('\n').map(line => `- ${line}`),
|
|
478
|
+
'+++ new',
|
|
479
|
+
...newText.split('\n').map(line => `+ ${line}`),
|
|
480
|
+
].join('\n');
|
|
481
|
+
return { kind: 'diff', title: path === null ? '修改文件' : `修改 ${path}`, detail: truncate(detail, 1600), added, removed };
|
|
482
|
+
}
|
|
483
|
+
if (patch !== null) {
|
|
484
|
+
return { kind: 'diff', title: path === null ? '应用补丁' : `修改 ${path}`, detail: truncate(patch, 1600) };
|
|
485
|
+
}
|
|
486
|
+
const content = firstString(args, ['content']);
|
|
487
|
+
if (toolName === 'write' && content !== null) {
|
|
488
|
+
return {
|
|
489
|
+
kind: 'diff',
|
|
490
|
+
title: path === null ? '写入文件' : `写入 ${path}`,
|
|
491
|
+
detail: truncate(content, 1000),
|
|
492
|
+
added: content.length === 0 ? 0 : content.split('\n').length,
|
|
493
|
+
removed: 0,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
if (path !== null)
|
|
497
|
+
return { kind: 'path', title: `修改 ${path}`, detail: path };
|
|
498
|
+
return undefined;
|
|
499
|
+
}
|
|
500
|
+
if (toolName === 'read' || toolName === 'grep' || toolName === 'glob') {
|
|
501
|
+
const pattern = firstString(args, ['pattern']);
|
|
502
|
+
return {
|
|
503
|
+
kind: 'path',
|
|
504
|
+
title: toolName === 'read' ? '读取文件' : toolName === 'grep' ? '搜索文本' : '查找文件',
|
|
505
|
+
...(path !== null ? { detail: path } : pattern !== null ? { detail: pattern } : {}),
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
if (toolName === 'web_search') {
|
|
509
|
+
const query = firstString(args, ['query', 'q']);
|
|
510
|
+
return query === null ? undefined : { kind: 'text', title: '联网搜索', detail: query };
|
|
511
|
+
}
|
|
512
|
+
if (toolName === 'web_fetch' || toolName === 'fetch' || toolName === 'browser') {
|
|
513
|
+
const url = firstString(args, ['url', 'href']);
|
|
514
|
+
return url === null ? undefined : { kind: 'url', title: '打开网页', detail: url };
|
|
515
|
+
}
|
|
516
|
+
if (raw === undefined || raw.length === 0)
|
|
517
|
+
return undefined;
|
|
518
|
+
return { kind: 'text', title: toolName, detail: truncate(raw, 1000) };
|
|
519
|
+
}
|
|
520
|
+
function asRecord(value) {
|
|
521
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
522
|
+
? value
|
|
523
|
+
: null;
|
|
524
|
+
}
|
|
525
|
+
function parseArgs(raw) {
|
|
526
|
+
if (raw === undefined || raw.trim().length === 0)
|
|
527
|
+
return null;
|
|
528
|
+
try {
|
|
529
|
+
return asRecord(JSON.parse(raw));
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return null;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function firstString(args, keys) {
|
|
536
|
+
if (args === null)
|
|
537
|
+
return null;
|
|
538
|
+
for (const key of keys) {
|
|
539
|
+
const value = args[key];
|
|
540
|
+
if (typeof value === 'string' && value.length > 0)
|
|
541
|
+
return value;
|
|
542
|
+
}
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
function safeStringify(value) {
|
|
546
|
+
try {
|
|
547
|
+
return JSON.stringify(value);
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function truncate(value, max) {
|
|
554
|
+
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
|
|
555
|
+
}
|
|
556
|
+
function grantKey(sessionId, toolName) {
|
|
557
|
+
return `${sessionId}\u0000${toolName}`;
|
|
558
|
+
}
|
|
559
|
+
/** Resolve an optional Cordis service without reading its property. */
|
|
560
|
+
function getService(ctx, name) {
|
|
561
|
+
try {
|
|
562
|
+
return ctx.get(name);
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
return undefined;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
//# sourceMappingURL=interactions.js.map
|