@gemies/sdk 10.3.0 → 10.5.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/CHANGELOG.md +60 -0
- package/package.json +1 -1
- package/src/components/ApprovalBar.tsx +131 -0
- package/src/components/GemieChatContent.tsx +54 -20
- package/src/components/GemieComposer.tsx +7 -0
- package/src/components/thread/AgentWork.tsx +262 -0
- package/src/components/thread/ApprovalCard.tsx +73 -71
- package/src/components/thread/CommandOutput.tsx +106 -0
- package/src/components/thread/GemieThread.tsx +4 -3
- package/src/components/thread/ThreadRow.tsx +21 -1
- package/src/hooks/useApprovalShortcuts.ts +93 -0
- package/src/lib/copy-en.ts +31 -4
- package/src/lib/copy-es.ts +31 -4
- package/src/realtime/contract.ts +18 -1
- package/src/realtime/react.tsx +8 -5
- package/src/runtime/approvals.ts +150 -13
- package/src/runtime/config.tsx +16 -4
- package/src/runtime/index.ts +9 -1
- package/src/runtime/model.ts +2 -0
- package/src/runtime/thread/agent-work.ts +192 -0
- package/src/runtime/thread/command-output.ts +51 -0
- package/src/runtime/use-approval-actions.ts +162 -0
- package/src/runtime/use-conversation-stream.ts +21 -7
- package/src/runtime/use-step-output.ts +42 -0
package/src/realtime/react.tsx
CHANGED
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
import { useRealtimeActivityStore } from './activity';
|
|
22
22
|
import { attachRealtimeStore } from './store';
|
|
23
23
|
import { acquireRealtime, type RealtimeConnection, type RealtimeListener } from './connection';
|
|
24
|
-
import type { RealtimeActivity, RealtimeFrame, RealtimeType } from './contract';
|
|
24
|
+
import type { RealtimeActivity, RealtimeFrame, RealtimeSignalType, RealtimeType } from './contract';
|
|
25
25
|
|
|
26
26
|
interface RealtimeHold {
|
|
27
27
|
readonly apiUrl: string;
|
|
@@ -158,12 +158,15 @@ export function useRealtimeReset(handler: () => void): void {
|
|
|
158
158
|
}
|
|
159
159
|
|
|
160
160
|
/**
|
|
161
|
-
* Follow a topic (`agent:<id>`, `agent-session:<id>`) while
|
|
162
|
-
*
|
|
161
|
+
* Follow a topic (`agent:<id>`, `agent-session:<id>`, `step-output:<conversation>:<call>`) while
|
|
162
|
+
* mounted, and hear its frames of one `type` (an agent run's detail by default). The server checks
|
|
163
|
+
* the person may; a refused topic simply never speaks. A `null` topic follows nothing: that is how
|
|
164
|
+
* a caller says "not now", and the subscription is released.
|
|
163
165
|
*/
|
|
164
166
|
export function useRealtimeTopic(
|
|
165
167
|
topic: string | null,
|
|
166
168
|
handler: (frame: RealtimeFrame) => void,
|
|
169
|
+
type: RealtimeSignalType = 'agent.activity',
|
|
167
170
|
): void {
|
|
168
171
|
const connection = useGemieRealtime();
|
|
169
172
|
const ref = useRef(handler);
|
|
@@ -171,14 +174,14 @@ export function useRealtimeTopic(
|
|
|
171
174
|
useEffect(() => {
|
|
172
175
|
if (!connection || !topic) return;
|
|
173
176
|
const release = connection.follow(topic);
|
|
174
|
-
const off = connection.on(
|
|
177
|
+
const off = connection.on(type, (frame) => {
|
|
175
178
|
if (frame.topic === topic) ref.current(frame);
|
|
176
179
|
});
|
|
177
180
|
return () => {
|
|
178
181
|
off();
|
|
179
182
|
release();
|
|
180
183
|
};
|
|
181
|
-
}, [connection, topic]);
|
|
184
|
+
}, [connection, topic, type]);
|
|
182
185
|
}
|
|
183
186
|
|
|
184
187
|
/**
|
package/src/runtime/approvals.ts
CHANGED
|
@@ -4,16 +4,45 @@
|
|
|
4
4
|
* During a turn with an external agent (Claude Code on the person's computer), the CLI may stop and
|
|
5
5
|
* ask whether it can run something there. The turn waits; the stream carries two named events:
|
|
6
6
|
*
|
|
7
|
-
* `alia.cli_permission_request` the CLI asks: which tool, on what.
|
|
8
|
-
* `alia.cli_permission_resolved` the answer was given, or the time ran out.
|
|
7
|
+
* `alia.cli_permission_request` the CLI asks: which tool, on what, and the answers it offers.
|
|
8
|
+
* `alia.cli_permission_resolved` the answer was given, or the time ran out, or the turn ended.
|
|
9
9
|
*
|
|
10
10
|
* This is the third-party CLI's prompt to the person who runs it, on their own machine. It is not
|
|
11
11
|
* an Oxy grant: nothing here reaches Oxy, and the SDK does not know the endpoint that carries the
|
|
12
12
|
* answer — the host does (`GemieRuntimeHost.onApprovalDecision`).
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
/**
|
|
16
|
+
* What the person answers with:
|
|
17
|
+
*
|
|
18
|
+
* `allow` this once.
|
|
19
|
+
* `allow_session` this tool on this target for the rest of the conversation's session.
|
|
20
|
+
* `deny` no; with the words the agent is told, when there are any.
|
|
21
|
+
* `cancel` no, and stop the turn.
|
|
22
|
+
*/
|
|
23
|
+
export type ApprovalDecision = 'allow' | 'allow_session' | 'deny' | 'cancel';
|
|
24
|
+
|
|
25
|
+
/** How a question ended: an answer, a timeout, or the turn going on (or ending) without one. */
|
|
26
|
+
export type ApprovalOutcome = ApprovalDecision | 'expired' | 'ended';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* One way to answer. `id` and `label` are the agent's own when it offered the option: the label is
|
|
30
|
+
* shown as given and the id goes back as given. A built-in option has no `label`; the thread names
|
|
31
|
+
* it in the person's language.
|
|
32
|
+
*/
|
|
33
|
+
export interface ApprovalOption {
|
|
34
|
+
readonly id: string;
|
|
35
|
+
readonly kind: ApprovalDecision;
|
|
36
|
+
readonly label?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What a host's `onApprovalDecision` carries beside the decision. */
|
|
40
|
+
export interface ApprovalDetails {
|
|
41
|
+
/** The agent's option the person picked; absent for a built-in answer. */
|
|
42
|
+
readonly optionId?: string;
|
|
43
|
+
/** Words for the agent, with a denial. */
|
|
44
|
+
readonly feedback?: string;
|
|
45
|
+
}
|
|
17
46
|
|
|
18
47
|
export interface ApprovalRequest {
|
|
19
48
|
readonly requestId: string;
|
|
@@ -24,16 +53,58 @@ export interface ApprovalRequest {
|
|
|
24
53
|
readonly summary?: string;
|
|
25
54
|
/** ISO time after which the CLI is told no. */
|
|
26
55
|
readonly expiresAt: string;
|
|
56
|
+
/** What can be answered. Always at least one way to say no. */
|
|
57
|
+
readonly options: readonly ApprovalOption[];
|
|
27
58
|
}
|
|
28
59
|
|
|
29
60
|
/** A request and where it stands: waiting for the person, or how it ended. */
|
|
30
61
|
export interface ApprovalEntry extends ApprovalRequest {
|
|
31
62
|
readonly outcome: 'pending' | ApprovalOutcome;
|
|
63
|
+
/** The person did not answer: their earlier "allow for this session" did. */
|
|
64
|
+
readonly auto?: boolean;
|
|
65
|
+
/** What the person told the agent with a denial, kept to show beside the answer. */
|
|
66
|
+
readonly feedback?: string;
|
|
32
67
|
}
|
|
33
68
|
|
|
34
69
|
const text = (value: unknown, max: number): string | undefined =>
|
|
35
70
|
typeof value === 'string' && value !== '' ? value.slice(0, max) : undefined;
|
|
36
71
|
|
|
72
|
+
const DECISIONS: readonly ApprovalDecision[] = ['allow', 'allow_session', 'deny', 'cancel'];
|
|
73
|
+
const isDecision = (value: unknown): value is ApprovalDecision =>
|
|
74
|
+
typeof value === 'string' && (DECISIONS as readonly string[]).includes(value);
|
|
75
|
+
|
|
76
|
+
/** What a server that predates the options offers: a yes and a no. */
|
|
77
|
+
export const DEFAULT_APPROVAL_OPTIONS: readonly ApprovalOption[] = [
|
|
78
|
+
{ id: 'allow', kind: 'allow' },
|
|
79
|
+
{ id: 'deny', kind: 'deny' },
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The options in a request frame, as given. Ids and labels are the agent's: they are not rewritten,
|
|
84
|
+
* only bounded. An option without a usable id or kind is dropped; a request that is left with no
|
|
85
|
+
* way to say no gets one, so a card never traps the person.
|
|
86
|
+
*/
|
|
87
|
+
function parseOptions(raw: unknown): readonly ApprovalOption[] {
|
|
88
|
+
if (!Array.isArray(raw)) return DEFAULT_APPROVAL_OPTIONS;
|
|
89
|
+
const options: ApprovalOption[] = [];
|
|
90
|
+
for (const item of raw.slice(0, 8)) {
|
|
91
|
+
if (item === null || typeof item !== 'object') continue;
|
|
92
|
+
const { id, kind, label } = item as Record<string, unknown>;
|
|
93
|
+
if (typeof id !== 'string' || id === '' || id.length > 80 || !isDecision(kind)) continue;
|
|
94
|
+
if (options.some((o) => o.id === id)) continue;
|
|
95
|
+
const shown = text(label, 80)?.trim();
|
|
96
|
+
options.push({ id, kind, ...(shown ? { label: shown } : {}) });
|
|
97
|
+
}
|
|
98
|
+
if (options.length === 0) return DEFAULT_APPROVAL_OPTIONS;
|
|
99
|
+
if (!options.some((o) => o.kind === 'deny' || o.kind === 'cancel')) {
|
|
100
|
+
options.push({
|
|
101
|
+
id: options.some((o) => o.id === 'deny') ? 'gemies:deny' : 'deny',
|
|
102
|
+
kind: 'deny',
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return options;
|
|
106
|
+
}
|
|
107
|
+
|
|
37
108
|
/** The request in an `alia.cli_permission_request` frame, or `null` when the frame is not one. */
|
|
38
109
|
export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
|
|
39
110
|
if (data === null || typeof data !== 'object') return null;
|
|
@@ -46,20 +117,27 @@ export function parseApprovalRequest(data: unknown): ApprovalRequest | null {
|
|
|
46
117
|
return null;
|
|
47
118
|
}
|
|
48
119
|
const summary = text(d.summary, 200);
|
|
49
|
-
return {
|
|
120
|
+
return {
|
|
121
|
+
requestId,
|
|
122
|
+
agentId,
|
|
123
|
+
tool,
|
|
124
|
+
...(summary ? { summary } : {}),
|
|
125
|
+
expiresAt,
|
|
126
|
+
options: parseOptions(d.options),
|
|
127
|
+
};
|
|
50
128
|
}
|
|
51
129
|
|
|
52
130
|
/** The answer in an `alia.cli_permission_resolved` frame, or `null` when the frame is not one. */
|
|
53
131
|
export function parseApprovalResolved(
|
|
54
132
|
data: unknown,
|
|
55
|
-
): { requestId: string; outcome: ApprovalOutcome } | null {
|
|
133
|
+
): { requestId: string; outcome: ApprovalOutcome; auto: boolean } | null {
|
|
56
134
|
if (data === null || typeof data !== 'object') return null;
|
|
57
135
|
const d = data as Record<string, unknown>;
|
|
58
136
|
const requestId = text(d.requestId, 100);
|
|
59
137
|
if (!requestId) return null;
|
|
60
138
|
const decision = d.decision;
|
|
61
|
-
if (decision
|
|
62
|
-
return { requestId, outcome: decision };
|
|
139
|
+
if (!isDecision(decision) && decision !== 'expired' && decision !== 'ended') return null;
|
|
140
|
+
return { requestId, outcome: decision, auto: d.auto === true };
|
|
63
141
|
}
|
|
64
142
|
|
|
65
143
|
/** A request arrived: waiting, once. A repeat of one already here changes nothing. */
|
|
@@ -76,12 +154,50 @@ export function withApprovalOutcome(
|
|
|
76
154
|
list: readonly ApprovalEntry[],
|
|
77
155
|
requestId: string,
|
|
78
156
|
outcome: ApprovalOutcome,
|
|
157
|
+
extras: { readonly auto?: boolean; readonly feedback?: string } = {},
|
|
79
158
|
): ApprovalEntry[] {
|
|
80
159
|
return list.map((entry) =>
|
|
81
|
-
entry.requestId === requestId && entry.outcome === 'pending'
|
|
160
|
+
entry.requestId === requestId && entry.outcome === 'pending'
|
|
161
|
+
? {
|
|
162
|
+
...entry,
|
|
163
|
+
outcome,
|
|
164
|
+
...(extras.auto ? { auto: true } : {}),
|
|
165
|
+
...(extras.feedback ? { feedback: extras.feedback } : {}),
|
|
166
|
+
}
|
|
167
|
+
: entry,
|
|
82
168
|
);
|
|
83
169
|
}
|
|
84
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Every question still waiting ends as `outcome`. For the moments the stream cannot say it itself
|
|
173
|
+
* — it broke, the person stopped the turn, the conversation changed — so no card stays pressable
|
|
174
|
+
* for a request nobody is waiting on.
|
|
175
|
+
*/
|
|
176
|
+
export function settlePending(
|
|
177
|
+
list: readonly ApprovalEntry[],
|
|
178
|
+
outcome: ApprovalOutcome,
|
|
179
|
+
): ApprovalEntry[] {
|
|
180
|
+
return list.some((entry) => entry.outcome === 'pending')
|
|
181
|
+
? list.map((entry) => (entry.outcome === 'pending' ? { ...entry, outcome } : entry))
|
|
182
|
+
: [...list];
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** What the person is being asked now: the oldest question still waiting, or `undefined`. */
|
|
186
|
+
export const firstPending = (list: readonly ApprovalEntry[]): ApprovalEntry | undefined =>
|
|
187
|
+
list.find((entry) => entry.outcome === 'pending');
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* What the person allowed for the rest of a conversation's session: one tool on one path or URL,
|
|
191
|
+
* until `expiresAt` or until they take it back.
|
|
192
|
+
*/
|
|
193
|
+
export interface ApprovalGrant {
|
|
194
|
+
readonly id: string;
|
|
195
|
+
readonly tool: string;
|
|
196
|
+
/** The path or URL allowed. */
|
|
197
|
+
readonly target: string;
|
|
198
|
+
readonly expiresAt: string;
|
|
199
|
+
}
|
|
200
|
+
|
|
85
201
|
/**
|
|
86
202
|
* What a host's `onApprovalDecision` rejects with when the question is no longer open (answered
|
|
87
203
|
* elsewhere, or its time ran out): the card then reads "Timed out" instead of offering a retry.
|
|
@@ -93,7 +209,28 @@ export class ApprovalExpiredError extends Error {
|
|
|
93
209
|
}
|
|
94
210
|
}
|
|
95
211
|
|
|
96
|
-
/**
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
212
|
+
/**
|
|
213
|
+
* The options in the order they are laid out: no on the left, yes on the right, as a pair of
|
|
214
|
+
* buttons reads. Options of one kind keep the agent's own order.
|
|
215
|
+
*/
|
|
216
|
+
const LAYOUT_RANK: Record<ApprovalDecision, number> = {
|
|
217
|
+
cancel: 0,
|
|
218
|
+
deny: 1,
|
|
219
|
+
allow_session: 2,
|
|
220
|
+
allow: 3,
|
|
221
|
+
};
|
|
222
|
+
export const orderedApprovalOptions = (options: readonly ApprovalOption[]): ApprovalOption[] =>
|
|
223
|
+
[...options].sort((a, b) => LAYOUT_RANK[a.kind] - LAYOUT_RANK[b.kind]);
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* What an option says. The agent's own label is shown exactly as it gave it; a built-in option is
|
|
227
|
+
* named by the person's language (`chat.approval.option.<kind>`).
|
|
228
|
+
*/
|
|
229
|
+
export const approvalOptionLabel = (option: ApprovalOption, t: (key: string) => string): string =>
|
|
230
|
+
option.label ?? t(`chat.approval.option.${option.kind}`);
|
|
231
|
+
|
|
232
|
+
/** The option to send for a decision: the first the question offers of that kind. */
|
|
233
|
+
export const optionOfKind = (
|
|
234
|
+
entry: Pick<ApprovalEntry, 'options'>,
|
|
235
|
+
kind: ApprovalDecision,
|
|
236
|
+
): ApprovalOption | undefined => entry.options.find((o) => o.kind === kind);
|
package/src/runtime/config.tsx
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createContext, type ReactNode, useContext, useMemo } from 'react';
|
|
2
2
|
import { GEMIES_API_URL } from '../lib/origins';
|
|
3
|
+
import type { ApprovalDecision, ApprovalDetails, ApprovalGrant } from './approvals';
|
|
3
4
|
import type { AgentRun } from './types';
|
|
4
5
|
import { GemieRealtimeProvider } from '../realtime/react';
|
|
5
6
|
|
|
@@ -123,13 +124,24 @@ export interface GemieRuntimeHost {
|
|
|
123
124
|
/**
|
|
124
125
|
* The person answered a coding CLI that asked for permission to run something on their own
|
|
125
126
|
* computer (`alia.cli_permission_request`, ADR 0043). The host carries the answer to Gemies; the
|
|
126
|
-
* promise rejects when it could not be sent
|
|
127
|
+
* promise rejects when it could not be sent, and with `ApprovalExpiredError` when the question is
|
|
128
|
+
* no longer open. `details` carries the agent's own option when the person picked one, and the
|
|
129
|
+
* words that go to the agent with a denial. Omitted, the request is shown with no way to answer.
|
|
127
130
|
*/
|
|
128
|
-
onApprovalDecision
|
|
131
|
+
onApprovalDecision?(
|
|
129
132
|
requestId: string,
|
|
130
133
|
agentId: string,
|
|
131
|
-
decision:
|
|
132
|
-
|
|
134
|
+
decision: ApprovalDecision,
|
|
135
|
+
details?: ApprovalDetails,
|
|
136
|
+
): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* What the person allowed for the rest of this conversation's session with a coding CLI
|
|
139
|
+
* ("always allow this session"). Read after such an answer, and shown in the thread with a way
|
|
140
|
+
* to take each one back. Omitted, nothing is listed.
|
|
141
|
+
*/
|
|
142
|
+
listApprovalGrants?(agentId: string, conversationId: string): Promise<readonly ApprovalGrant[]>;
|
|
143
|
+
/** Takes one allowance back: the next such question is asked again. */
|
|
144
|
+
revokeApprovalGrant?(agentId: string, grantId: string): Promise<void>;
|
|
133
145
|
/** The agent's row in the host's list, ahead of the server: your line, then her answer. */
|
|
134
146
|
onTurnPreview?: (agentId: string | null | undefined, text: string) => void;
|
|
135
147
|
/**
|
package/src/runtime/index.ts
CHANGED
|
@@ -15,7 +15,15 @@
|
|
|
15
15
|
|
|
16
16
|
export { GemieRuntimeProvider, useGemieRuntime } from './config';
|
|
17
17
|
export { ApprovalExpiredError } from './approvals';
|
|
18
|
-
export type {
|
|
18
|
+
export type {
|
|
19
|
+
ApprovalDecision,
|
|
20
|
+
ApprovalDetails,
|
|
21
|
+
ApprovalEntry,
|
|
22
|
+
ApprovalGrant,
|
|
23
|
+
ApprovalOption,
|
|
24
|
+
ApprovalOutcome,
|
|
25
|
+
ApprovalRequest,
|
|
26
|
+
} from './approvals';
|
|
19
27
|
export type {
|
|
20
28
|
GemieArtifact,
|
|
21
29
|
GemieRuntimeConfig,
|
package/src/runtime/model.ts
CHANGED
|
@@ -13,7 +13,9 @@ export * from './power-levels';
|
|
|
13
13
|
export { englishCopy } from '../lib/copy';
|
|
14
14
|
export type { Translate } from '../lib/copy';
|
|
15
15
|
export * from './thread/agent-activity';
|
|
16
|
+
export * from './thread/agent-work';
|
|
16
17
|
export * from './thread/automation-labels';
|
|
18
|
+
export * from './thread/command-output';
|
|
17
19
|
export * from './thread/conversation-export';
|
|
18
20
|
export * from './thread/file-changes';
|
|
19
21
|
export * from './thread/message-days';
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { toolCallStatus } from '../../lib/tool-call-status';
|
|
2
|
+
import type { ToolInvocation } from '../types';
|
|
3
|
+
import { type CallFileChange, fileChangesOf } from './file-changes';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What a coding agent did in a turn, as one work log: the tool calls of an external agent
|
|
7
|
+
* (Codex, Claude Code, OpenCode on the person's computer, ADR 0043 §5) in the order they started,
|
|
8
|
+
* each a step with what it is, where it stands and how long it took.
|
|
9
|
+
*
|
|
10
|
+
* Pure: the stored invocations go in, the log the thread draws comes out. A turn has ONE log, not
|
|
11
|
+
* one per run of consecutive calls: the turn stores its calls beside its text, not between, so the
|
|
12
|
+
* text cannot split a run. Calls that draw their own card (weather, a chart, a question) are not
|
|
13
|
+
* steps; they never are an external agent's.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* An external agent's step is stored under its CLI's own id with this prefix (the API's
|
|
18
|
+
* `EXTERNAL_STEP_PREFIX`), which is how a step of one is told from a tool of the turn's own model.
|
|
19
|
+
*/
|
|
20
|
+
export const EXTERNAL_STEP_PREFIX = 'ext_';
|
|
21
|
+
|
|
22
|
+
export function isExternalStep(call: Pick<ToolInvocation, 'toolCallId'>): boolean {
|
|
23
|
+
return call.toolCallId.startsWith(EXTERNAL_STEP_PREFIX);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What kind of work a step is: it picks the glyph, and whether the step has output to show. */
|
|
27
|
+
export type AgentStepKind = 'command' | 'read' | 'edit' | 'search' | 'web' | 'tool';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* - `running`: still going in a live turn.
|
|
31
|
+
* - `ok`: it finished.
|
|
32
|
+
* - `failed`: it finished with an error (a CLI error, a non-zero exit).
|
|
33
|
+
* - `declined`: the person said no to it.
|
|
34
|
+
* - `interrupted`: it never finished and its turn is over.
|
|
35
|
+
*/
|
|
36
|
+
export type AgentStepStatus = 'running' | 'ok' | 'failed' | 'declined' | 'interrupted';
|
|
37
|
+
|
|
38
|
+
export interface StepOutput {
|
|
39
|
+
readonly text: string;
|
|
40
|
+
/** What came before `text` was dropped to keep it a bounded size. */
|
|
41
|
+
readonly truncated: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface AgentStep {
|
|
45
|
+
/** The stored call's id: what a step is addressed by (its realtime topic, its row key). */
|
|
46
|
+
readonly id: string;
|
|
47
|
+
readonly kind: AgentStepKind;
|
|
48
|
+
/** The tool the CLI named (`Bash`, `Read`, `Edit`…). */
|
|
49
|
+
readonly tool: string;
|
|
50
|
+
/** What it acts on: the command, the path, the pattern. */
|
|
51
|
+
readonly target: string | undefined;
|
|
52
|
+
readonly status: AgentStepStatus;
|
|
53
|
+
/** Epoch ms the step began, when the server said. */
|
|
54
|
+
readonly startedAt: number | undefined;
|
|
55
|
+
/** How long it ran, once it finished. */
|
|
56
|
+
readonly durationMs: number | undefined;
|
|
57
|
+
readonly exitCode: number | undefined;
|
|
58
|
+
/** What a command printed, as stored (bounded). Absent for a step with none. */
|
|
59
|
+
readonly output: StepOutput | undefined;
|
|
60
|
+
/** Whether the step's output is something to show: a command's, running or finished. */
|
|
61
|
+
readonly hasOutput: boolean;
|
|
62
|
+
/** The files an edit changed, as the diff viewer draws them; none for any other step. */
|
|
63
|
+
readonly changes: readonly CallFileChange[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface AgentWork {
|
|
67
|
+
readonly steps: readonly AgentStep[];
|
|
68
|
+
readonly running: number;
|
|
69
|
+
readonly failed: number;
|
|
70
|
+
/** First step's start to the last step's end, when the server stamped them. */
|
|
71
|
+
readonly startedAt: number | undefined;
|
|
72
|
+
readonly endedAt: number | undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const KINDS: ReadonlyArray<readonly [AgentStepKind, readonly string[]]> = [
|
|
76
|
+
['command', ['bash', 'shell', 'exec', 'execcommand', 'command', 'terminal', 'run', 'powershell']],
|
|
77
|
+
['read', ['read', 'view', 'cat', 'open']],
|
|
78
|
+
['edit', ['edit', 'write', 'multiedit', 'notebookedit', 'patch', 'applypatch', 'filechange']],
|
|
79
|
+
['search', ['grep', 'glob', 'ls', 'find', 'list', 'search', 'codesearch']],
|
|
80
|
+
['web', ['websearch', 'webfetch', 'fetch', 'browse', 'browser']],
|
|
81
|
+
];
|
|
82
|
+
|
|
83
|
+
/** The kind of work a CLI's tool name is. Names differ by CLI (`Bash`, `Shell`, `exec_command`). */
|
|
84
|
+
export function stepKind(tool: string): AgentStepKind {
|
|
85
|
+
const name = tool.toLowerCase().replace(/[^a-z]/g, '');
|
|
86
|
+
for (const [kind, names] of KINDS) if (names.includes(name)) return kind;
|
|
87
|
+
return 'tool';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
91
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
92
|
+
? (value as Record<string, unknown>)
|
|
93
|
+
: undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const text = (value: unknown): string | undefined =>
|
|
97
|
+
typeof value === 'string' && value !== '' ? value : undefined;
|
|
98
|
+
const count = (value: unknown): number | undefined =>
|
|
99
|
+
typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
100
|
+
|
|
101
|
+
function stampOf(value: unknown): number | undefined {
|
|
102
|
+
const at = typeof value === 'string' ? Date.parse(value) : Number.NaN;
|
|
103
|
+
return Number.isNaN(at) ? undefined : at;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function statusOf(call: ToolInvocation, live: boolean, exitCode: number | undefined) {
|
|
107
|
+
const result = record(call.result);
|
|
108
|
+
const reported = result?.status;
|
|
109
|
+
if (reported === 'declined' || reported === 'denied') return 'declined';
|
|
110
|
+
const base = toolCallStatus(call, live);
|
|
111
|
+
if (base === 'running') return 'running';
|
|
112
|
+
if (base === 'interrupted') return 'interrupted';
|
|
113
|
+
if (base === 'error' || reported === 'error' || (exitCode !== undefined && exitCode !== 0)) {
|
|
114
|
+
return 'failed';
|
|
115
|
+
}
|
|
116
|
+
return 'ok';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** One stored call as a step. */
|
|
120
|
+
export function agentStepOf(call: ToolInvocation, live: boolean): AgentStep {
|
|
121
|
+
const args = record(call.args);
|
|
122
|
+
const result = call.state === 'result' ? record(call.result) : undefined;
|
|
123
|
+
const kind = stepKind(call.toolName);
|
|
124
|
+
const exitCode = count(result?.exitCode);
|
|
125
|
+
const stored = text(result?.output);
|
|
126
|
+
return {
|
|
127
|
+
id: call.toolCallId,
|
|
128
|
+
kind,
|
|
129
|
+
tool: call.toolName,
|
|
130
|
+
target: text(args?.summary) ?? text(result?.summary),
|
|
131
|
+
status: statusOf(call, live, exitCode),
|
|
132
|
+
startedAt: stampOf(args?.startedAt),
|
|
133
|
+
durationMs: count(result?.durationMs),
|
|
134
|
+
exitCode,
|
|
135
|
+
output:
|
|
136
|
+
stored === undefined
|
|
137
|
+
? undefined
|
|
138
|
+
: { text: stored, truncated: result?.outputTruncated === true },
|
|
139
|
+
hasOutput: kind === 'command' || stored !== undefined,
|
|
140
|
+
changes: fileChangesOf(call),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The turn's work log, or `null` when an external agent did nothing in it.
|
|
146
|
+
*
|
|
147
|
+
* `live` is whether the turn is still running: a call with no result is `running` then and
|
|
148
|
+
* `interrupted` after, so a log never says "done" about work that did not finish.
|
|
149
|
+
*/
|
|
150
|
+
export function buildAgentWork(
|
|
151
|
+
calls: readonly ToolInvocation[] | undefined,
|
|
152
|
+
live: boolean,
|
|
153
|
+
): AgentWork | null {
|
|
154
|
+
const steps = (calls ?? []).filter(isExternalStep).map((call) => agentStepOf(call, live));
|
|
155
|
+
if (steps.length === 0) return null;
|
|
156
|
+
const first = steps.find((step) => step.startedAt !== undefined);
|
|
157
|
+
const ends = steps.flatMap((step) =>
|
|
158
|
+
step.startedAt !== undefined && step.durationMs !== undefined
|
|
159
|
+
? [step.startedAt + step.durationMs]
|
|
160
|
+
: [],
|
|
161
|
+
);
|
|
162
|
+
return {
|
|
163
|
+
steps,
|
|
164
|
+
running: steps.filter((step) => step.status === 'running').length,
|
|
165
|
+
failed: steps.filter((step) => step.status === 'failed').length,
|
|
166
|
+
startedAt: first?.startedAt,
|
|
167
|
+
endedAt: ends.length > 0 ? Math.max(...ends) : undefined,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* How long the work took: to its last finished step, or — while a step is still running — to
|
|
173
|
+
* `now`. `undefined` when the server stamped nothing (a turn stored before steps carried times).
|
|
174
|
+
*/
|
|
175
|
+
export function workElapsedMs(work: AgentWork, now: number): number | undefined {
|
|
176
|
+
if (work.startedAt === undefined) return undefined;
|
|
177
|
+
const end = work.running > 0 ? now : work.endedAt;
|
|
178
|
+
return end === undefined ? undefined : Math.max(0, end - work.startedAt);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** A step's duration as a row prints it: `340ms`, `2.4s`, `1m 5s`. */
|
|
182
|
+
export function formatStepDuration(ms: number): string {
|
|
183
|
+
if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`;
|
|
184
|
+
if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
|
|
185
|
+
const total = Math.round(ms / 1000);
|
|
186
|
+
const hours = Math.floor(total / 3600);
|
|
187
|
+
const minutes = Math.floor((total % 3600) / 60);
|
|
188
|
+
const seconds = total % 60;
|
|
189
|
+
if (hours > 0) return `${hours}h ${minutes}m`;
|
|
190
|
+
if (minutes > 0) return `${minutes}m ${seconds}s`;
|
|
191
|
+
return `${seconds}s`;
|
|
192
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A command's output as the thread draws it: plain text, readable, bounded.
|
|
3
|
+
*
|
|
4
|
+
* What a CLI prints is for a terminal: colour escapes, a progress bar redrawn in place with `\r`,
|
|
5
|
+
* a bell. None of that means anything in a conversation, and rendering escapes is how terminal
|
|
6
|
+
* output becomes a way to put things on a person's screen, so they are removed rather than drawn.
|
|
7
|
+
* The text that remains is what a person would copy.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Characters of output the thread holds and draws at most (the server sends no more than its tail). */
|
|
11
|
+
export const COMMAND_OUTPUT_VIEW_CHARS = 32 * 1024;
|
|
12
|
+
|
|
13
|
+
// Control Sequence Introducer (`ESC [ … final`), Operating System Command (`ESC ] … BEL | ST`), and the
|
|
14
|
+
// two-character escapes (`ESC c`, `ESC =`…). Built from char codes so no control byte is written in
|
|
15
|
+
// the source.
|
|
16
|
+
const ESC = String.fromCharCode(0x1b);
|
|
17
|
+
const BEL = String.fromCharCode(0x07);
|
|
18
|
+
const CSI = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, 'g');
|
|
19
|
+
const OSC = new RegExp(`${ESC}\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`, 'g');
|
|
20
|
+
const SHORT = new RegExp(`${ESC}[@-Z\\\\-_=>]`, 'g');
|
|
21
|
+
// Every control character but tab and newline (and `\r`, handled on its own).
|
|
22
|
+
const CONTROLS = new RegExp(
|
|
23
|
+
`[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(0x0b)}${String.fromCharCode(0x0c)}${String.fromCharCode(0x0e)}-${String.fromCharCode(0x1f)}${String.fromCharCode(0x7f)}]`,
|
|
24
|
+
'g',
|
|
25
|
+
);
|
|
26
|
+
|
|
27
|
+
/** `text` without terminal escapes, bells and the like. */
|
|
28
|
+
export function stripAnsi(text: string): string {
|
|
29
|
+
return text.replace(OSC, '').replace(CSI, '').replace(SHORT, '').replace(CONTROLS, '');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A line a progress bar redrew with `\r` is the last thing it drew; `\r\n` is a newline.
|
|
34
|
+
*/
|
|
35
|
+
function settleCarriageReturns(text: string): string {
|
|
36
|
+
if (!text.includes('\r')) return text;
|
|
37
|
+
return text
|
|
38
|
+
.replace(/\r\n/g, '\n')
|
|
39
|
+
.split('\n')
|
|
40
|
+
.map((line) => {
|
|
41
|
+
const last = line.lastIndexOf('\r');
|
|
42
|
+
return last === -1 ? line : line.slice(last + 1);
|
|
43
|
+
})
|
|
44
|
+
.join('\n');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** What the thread draws for a step's output. */
|
|
48
|
+
export function displayOutput(raw: string): string {
|
|
49
|
+
const text = settleCarriageReturns(stripAnsi(raw));
|
|
50
|
+
return text.length > COMMAND_OUTPUT_VIEW_CHARS ? text.slice(-COMMAND_OUTPUT_VIEW_CHARS) : text;
|
|
51
|
+
}
|