@stigmer/client 0.1.3 → 0.2.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.
Files changed (61) hide show
  1. package/app-handover.d.ts +119 -0
  2. package/app-handover.d.ts.map +1 -0
  3. package/app-handover.js +523 -0
  4. package/app-handover.js.map +1 -0
  5. package/gen/organization.d.ts +2 -0
  6. package/gen/organization.d.ts.map +1 -1
  7. package/gen/organization.js +8 -0
  8. package/gen/organization.js.map +1 -1
  9. package/iam-principal.d.ts +11 -0
  10. package/iam-principal.d.ts.map +1 -1
  11. package/iam-principal.js +16 -0
  12. package/iam-principal.js.map +1 -1
  13. package/index.d.ts +11 -5
  14. package/index.d.ts.map +1 -1
  15. package/index.js +10 -3
  16. package/index.js.map +1 -1
  17. package/package.json +3 -3
  18. package/platform.d.ts +41 -3
  19. package/platform.d.ts.map +1 -1
  20. package/platform.js +56 -3
  21. package/platform.js.map +1 -1
  22. package/run/format-elapsed.d.ts +10 -0
  23. package/run/format-elapsed.d.ts.map +1 -0
  24. package/run/format-elapsed.js +25 -0
  25. package/run/format-elapsed.js.map +1 -0
  26. package/run/step-words.d.ts +78 -0
  27. package/run/step-words.d.ts.map +1 -0
  28. package/run/step-words.js +316 -0
  29. package/run/step-words.js.map +1 -0
  30. package/run/tool-view.d.ts +26 -2
  31. package/run/tool-view.d.ts.map +1 -1
  32. package/run/tool-view.js +83 -17
  33. package/run/tool-view.js.map +1 -1
  34. package/run/turn-activity.d.ts +9 -7
  35. package/run/turn-activity.d.ts.map +1 -1
  36. package/run/turn-activity.js +24 -144
  37. package/run/turn-activity.js.map +1 -1
  38. package/run/turn-ending.d.ts +59 -0
  39. package/run/turn-ending.d.ts.map +1 -0
  40. package/run/turn-ending.js +394 -0
  41. package/run/turn-ending.js.map +1 -0
  42. package/run/turn-steps.d.ts +16 -0
  43. package/run/turn-steps.d.ts.map +1 -0
  44. package/run/turn-steps.js +65 -0
  45. package/run/turn-steps.js.map +1 -0
  46. package/session-events.d.ts +3 -1
  47. package/session-events.d.ts.map +1 -1
  48. package/session-events.js +1 -0
  49. package/session-events.js.map +1 -1
  50. package/src/app-handover.ts +613 -0
  51. package/src/gen/organization.ts +7 -0
  52. package/src/iam-principal.ts +21 -0
  53. package/src/index.ts +49 -1
  54. package/src/platform.ts +80 -3
  55. package/src/run/format-elapsed.ts +22 -0
  56. package/src/run/step-words.ts +360 -0
  57. package/src/run/tool-view.ts +102 -19
  58. package/src/run/turn-activity.ts +27 -146
  59. package/src/run/turn-ending.ts +475 -0
  60. package/src/run/turn-steps.ts +81 -0
  61. package/src/session-events.ts +4 -1
@@ -118,6 +118,27 @@ export function isAppUserAccount(
118
118
  );
119
119
  }
120
120
 
121
+ /**
122
+ * Whether an access-list entry is a person who signed in to Stigmer itself:
123
+ * a person kind whose identity origin is `direct` (the deployment's own
124
+ * sign-in) or `federated` (an organization's own identity provider). App
125
+ * users and service accounts read `false`, and so does an entry the server
126
+ * could not resolve, which carries no origin, and a team. This is the
127
+ * positive rule for "someone joined the team", where reading everything
128
+ * that is not an app user or a service account would count an unresolved
129
+ * entry as a teammate.
130
+ */
131
+ export function isPersonAccount(
132
+ view: Pick<ApiResourceRefView, "kind" | "identityOrigin">,
133
+ ): boolean {
134
+ const mode = view.identityOrigin?.provisioningMode;
135
+ return (
136
+ view.kind === PERSON_KIND &&
137
+ (mode === IdentityAccountProvisioningMode.direct ||
138
+ mode === IdentityAccountProvisioningMode.federated)
139
+ );
140
+ }
141
+
121
142
  /**
122
143
  * Whether an access-list entry is an organization's service account: a
123
144
  * person kind whose identity origin is `service_account`. An entry the
package/src/index.ts CHANGED
@@ -40,6 +40,26 @@ export {
40
40
  buildEmbedSnippet,
41
41
  } from "./chat-link.js";
42
42
 
43
+ // The code that puts an agent's chat in a builder's own app (token route and
44
+ // chat, per stack; framework-free)
45
+ export {
46
+ APP_HANDOVER_STACKS,
47
+ APP_TOKEN_ROUTE,
48
+ APP_API_KEY_VARIABLE,
49
+ APP_DEV_USER_VARIABLE,
50
+ APP_CHAT_COMPONENT,
51
+ APP_TOKEN_ROUTE_PORT,
52
+ buildAppHandover,
53
+ } from "./app-handover.js";
54
+ export type {
55
+ AppHandover,
56
+ AppHandoverFile,
57
+ AppHandoverInput,
58
+ AppHandoverLanguage,
59
+ AppHandoverMode,
60
+ AppHandoverStack,
61
+ } from "./app-handover.js";
62
+
43
63
  // References the server returned (a deleted target has an id and no slug)
44
64
  export {
45
65
  isDeletedReference,
@@ -114,6 +134,7 @@ export {
114
134
  granteeFromView,
115
135
  granteeKey,
116
136
  isAppUserAccount,
137
+ isPersonAccount,
117
138
  isServiceAccount,
118
139
  } from "./iam-principal.js";
119
140
  export {
@@ -164,6 +185,7 @@ export {
164
185
  export {
165
186
  PlatformClient,
166
187
  type EnvironmentAvailability,
188
+ type HelpLink,
167
189
  type NativeSignIn,
168
190
  type ServerInfo,
169
191
  } from "./platform.js";
@@ -397,11 +419,13 @@ export {
397
419
  resolveToolKind,
398
420
  resolveToolKindByName,
399
421
  normalizeToolResult,
422
+ editAttemptOf,
400
423
  SHELL_INTENT_ARG_FIELD,
401
424
  extractShellIntent,
402
425
  shellIntentFromArgs,
403
426
  isSecretArgKey,
404
427
  redactSecretArgs,
428
+ type FileLineRange,
405
429
  type ToolResultView,
406
430
  type ToolSearchMatch,
407
431
  type ToolContentBlock,
@@ -423,13 +447,36 @@ export { isTerminalPhase, turnPhaseOf } from "./run/run-phases.js";
423
447
  export {
424
448
  activityPhrase,
425
449
  describeTurnActivity,
426
- formatElapsed,
450
+ SANDBOX_WAIT_PHRASE,
427
451
  settledStepsPhrase,
428
452
  stepsSpanMs,
429
453
  type TodoProgress,
430
454
  type TurnActivity,
431
455
  type TurnProgress,
432
456
  } from "./run/turn-activity.js";
457
+ export { formatElapsed } from "./run/format-elapsed.js";
458
+ export {
459
+ failureWords,
460
+ humanizeToolName,
461
+ lineRangeWords,
462
+ searchCountWords,
463
+ stepPhrase,
464
+ stepTense,
465
+ type StepPhrase,
466
+ type StepPhraseOptions,
467
+ type StepTense,
468
+ } from "./run/step-words.js";
469
+ export { turnSteps, type PlanItem, type TurnSteps } from "./run/turn-steps.js";
470
+ export {
471
+ describeTurnEnding,
472
+ type DescribeTurnEndingInput,
473
+ type TurnEnding,
474
+ type TurnEndingAct,
475
+ type TurnEndingLink,
476
+ type TurnEndingNames,
477
+ type TurnEndingTone,
478
+ type TurnEndingViewer,
479
+ } from "./run/turn-ending.js";
433
480
  export { backgroundCommandText, backgroundEndingLine, backgroundEndingPhrase } from "./run/background-command.js";
434
481
  // A session's events, folded: the one model every client reads a
435
482
  // conversation from (@stigmer/session-log), and the helpers that follow a
@@ -481,6 +528,7 @@ export {
481
528
  type TurnOpenOperation,
482
529
  type TurnPhase,
483
530
  type TurnStatus,
531
+ type TurnStopDetail,
484
532
  type UserMessage,
485
533
  type UserMessageItem,
486
534
  } from "@stigmer/session-log";
package/src/platform.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  import type {
9
9
  GetLicenseStatusOutput,
10
10
  GetServerInfoOutput,
11
+ HelpLink as HelpLinkProto,
11
12
  ServerEdition,
12
13
  } from "@stigmer/apis/ai/stigmer/platform/v1/server_info_pb";
13
14
  import {
@@ -15,6 +16,8 @@ import {
15
16
  ModelOnEngineSchema,
16
17
  } from "@stigmer/apis/ai/stigmer/platform/v1/model_readiness_pb";
17
18
  import type { GetModelReadinessOutput } from "@stigmer/apis/ai/stigmer/platform/v1/model_readiness_pb";
19
+ import { GetOnboardingFunnelInputSchema } from "@stigmer/apis/ai/stigmer/platform/v1/onboarding_funnel_pb";
20
+ import type { GetOnboardingFunnelOutput } from "@stigmer/apis/ai/stigmer/platform/v1/onboarding_funnel_pb";
18
21
  import type { Harness } from "@stigmer/apis/ai/stigmer/agentic/session/v1/enum_pb";
19
22
  import { wrapError } from "./gen/errors.js";
20
23
  import {
@@ -75,6 +78,26 @@ export interface ServerInfo {
75
78
  * offers no sign-in to an installed app.
76
79
  */
77
80
  readonly nativeSignIn: NativeSignIn | undefined;
81
+ /**
82
+ * Where a person stuck on this server asks for help, as its operator set
83
+ * it: an address and the words to show for it. Show it on your own
84
+ * screens (sign-in, the page's chrome, every failure); never inside an
85
+ * app a builder made for their own users, whose help is the builder's.
86
+ *
87
+ * `undefined` when the operator set none, on a server released before
88
+ * the field, and when the server announced an address that is not an
89
+ * absolute `https:`, `http:` or `mailto:` one, which is never handed on:
90
+ * show no help link then, rather than a guess.
91
+ */
92
+ readonly help: HelpLink | undefined;
93
+ }
94
+
95
+ /** Where to ask for help, as {@link ServerInfo.help} reports it. */
96
+ export interface HelpLink {
97
+ /** An absolute `https:`, `http:` or `mailto:` address. */
98
+ readonly url: string;
99
+ /** The words to show for it, at most 40 characters; plain text, never markup. */
100
+ readonly label: string;
78
101
  }
79
102
 
80
103
  /** How an installed app signs in, as {@link ServerInfo.nativeSignIn} reports it. */
@@ -101,8 +124,38 @@ export interface EnvironmentAvailability {
101
124
  readonly packages: boolean;
102
125
  }
103
126
 
127
+ /** The schemes a help address may carry: a web page or a mail address. */
128
+ const HELP_LINK_SCHEMES: ReadonlySet<string> = new Set(["https:", "http:", "mailto:"]);
129
+
130
+ /** The longest label a server announces (the server's own limit). */
131
+ const HELP_LABEL_MAX = 40;
132
+
133
+ /**
134
+ * The announced help link, or undefined when there is none or it is not one
135
+ * a client may render: a server checks its operator's address at boot, and
136
+ * a client checks again because it meets servers it did not build. A label
137
+ * that is empty or too long is replaced by "Get help", the server's own
138
+ * default, rather than dropping a good address.
139
+ */
140
+ function helpLinkOf(help: HelpLinkProto | undefined): HelpLink | undefined {
141
+ if (help === undefined) return undefined;
142
+ let parsed: URL;
143
+ try {
144
+ parsed = new URL(help.url);
145
+ } catch {
146
+ return undefined;
147
+ }
148
+ if (!HELP_LINK_SCHEMES.has(parsed.protocol)) return undefined;
149
+ const label = help.label.trim();
150
+ return {
151
+ url: help.url,
152
+ label: label === "" || [...label].length > HELP_LABEL_MAX ? "Get help" : label,
153
+ };
154
+ }
155
+
104
156
  /**
105
- * Client for platform-level queries (server info, capabilities, license).
157
+ * Client for platform-level queries (server info, capabilities, license,
158
+ * the operator's onboarding count).
106
159
  *
107
160
  * The {@link getServerInfo} method is the authoritative source for
108
161
  * deployment mode detection. It replaces URL-based hostname guessing
@@ -118,8 +171,8 @@ export class PlatformClient {
118
171
 
119
172
  /**
120
173
  * Retrieve the connected server's edition, version, authentication
121
- * posture, how an installed app signs in, whether it holds one
122
- * organization, and what an Environment does there. Answered before
174
+ * posture, how an installed app signs in, where to ask for help,
175
+ * whether it holds one organization, and what an Environment does there. Answered before
123
176
  * sign-in: no credential is needed.
124
177
  *
125
178
  * Maps the proto {@link ServerEdition} to a {@link DeploymentMode}
@@ -147,6 +200,7 @@ export class PlatformClient {
147
200
  audience: resp.nativeSignIn.audience,
148
201
  clientId: resp.nativeSignIn.clientId,
149
202
  },
203
+ help: helpLinkOf(resp.help),
150
204
  singleOrg: resp.singleOrg,
151
205
  environments:
152
206
  resp.environments === undefined
@@ -208,4 +262,27 @@ export class PlatformClient {
208
262
  throw wrapError(e);
209
263
  }
210
264
  }
265
+
266
+ /**
267
+ * How far the organizations made in a window got on the journey from a
268
+ * first agent to their users: how many were made, how many were left out
269
+ * as the operator's own, and how many have each of the six steps done.
270
+ * Counts only. A platform operator's read; anyone else is refused with
271
+ * PERMISSION_DENIED, and a server older than the read answers
272
+ * UNIMPLEMENTED.
273
+ *
274
+ * @param window.from - A UTC calendar day ("2026-11-01"), from its first
275
+ * instant, or an RFC 3339 instant; inclusive.
276
+ * @param window.to - A UTC calendar day, through its last instant, or an
277
+ * RFC 3339 instant; inclusive.
278
+ */
279
+ async getOnboardingFunnel(window: { readonly from: string; readonly to: string }): Promise<GetOnboardingFunnelOutput> {
280
+ try {
281
+ return await this.platform.getOnboardingFunnel(
282
+ create(GetOnboardingFunnelInputSchema, { fromDate: window.from, toDate: window.to }),
283
+ );
284
+ } catch (e) {
285
+ throw wrapError(e);
286
+ }
287
+ }
211
288
  }
@@ -0,0 +1,22 @@
1
+ // How long something took or has been going, as every surface says it (the
2
+ // session view, the terminal, the CLI). A module of its own, with nothing
3
+ // else in it, so a surface that only says a duration loads only this.
4
+
5
+ /**
6
+ * A span of time in at most two units, the larger first, the smaller always
7
+ * two digits so a ticking time keeps its width: "42s", "1m 05s", "15m 00s",
8
+ * "1h 03m", "2d 05h". Every surface that says how long something took or has
9
+ * been going says it this way (the session view, the terminal, the CLI).
10
+ * Seconds are floored, so a span never reads longer than it was; a negative
11
+ * span reads "0s".
12
+ */
13
+ export function formatElapsed(ms: number): string {
14
+ const two = (n: number): string => String(n).padStart(2, "0");
15
+ const seconds = Math.max(0, Math.floor(ms / 1000));
16
+ if (seconds < 60) return `${seconds}s`;
17
+ const minutes = Math.floor(seconds / 60);
18
+ if (minutes < 60) return `${minutes}m ${two(seconds % 60)}s`;
19
+ const hours = Math.floor(minutes / 60);
20
+ if (hours < 24) return `${hours}h ${two(minutes % 60)}m`;
21
+ return `${Math.floor(hours / 24)}d ${two(hours % 24)}h`;
22
+ }
@@ -0,0 +1,360 @@
1
+ // The words a tool call reads as: one table of every kind's verbs, in the
2
+ // present (while it runs), the past (once it returned) and the failed form,
3
+ // beside the noun a settled stretch counts it by. The working turn's phrase
4
+ // (`activityPhrase`), the settled stretch's roll-up (`settledStepsPhrase`)
5
+ // and each step's own line (`stepPhrase`) all read this table, so the three
6
+ // cannot describe one call three ways.
7
+ //
8
+ // A step's line reads only what the call carries: its kind
9
+ // (`resolveToolKind`), its input (a file's path, a search's pattern and
10
+ // folder, a page's address, the agent's own description of a command) and
11
+ // whether it returned, failed, or is still open. A command that exited
12
+ // non-zero failed even when the engine did not mark it an error.
13
+ //
14
+ // Trade-offs:
15
+ // - A connected app's tool (MCP) and a tool the kit does not know read as
16
+ // the tool's own name, humanized ("Create issue"), with no tense: a past
17
+ // tense guessed from an arbitrary name ("Get status", "List merge
18
+ // requests") would misread, and the name is exact.
19
+ // - A search for files by name (glob) reads "Found files matching", told
20
+ // apart from a search in files' text by the tool's name, as the kind
21
+ // table itself is.
22
+ // - Targets are cut short (`TARGET_MAX`) so a line stays one line.
23
+
24
+ import type { ToolUse } from "@stigmer/session-log";
25
+ import { normalizeToolResult, resolveToolKind, type FileLineRange, type ToolKind, type ToolResultView } from "./tool-view.js";
26
+
27
+ /** How a step stands: running, returned, failed, or stopped before it returned (its turn ended). */
28
+ export type StepTense = "present" | "past" | "failed" | "stopped";
29
+
30
+ /** A step's words: the line, how it stands, and what it names beside the line. */
31
+ export interface StepPhrase {
32
+ /** The line: "Edited invoice.ts", "Searched for round( in src/billing", "Couldn't read notes.md". */
33
+ readonly text: string;
34
+ readonly tense: StepTense;
35
+ /** The folder of the file the line names, or where a search at work looks ("src/billing"); "" when it names none or the file sits at the root. */
36
+ readonly folder: string;
37
+ /** The connected app an MCP call belongs to; "" for a built-in tool. */
38
+ readonly app: string;
39
+ }
40
+
41
+ /** One form of a kind's words: with a target ("Reading" + " invoice.ts") and without one ("Reading a file"). */
42
+ type Form = readonly [withTarget: string, alone: string];
43
+
44
+ /** Every kind's words in each tense, and the past verb and noun a settled stretch counts it by. */
45
+ interface KindWords {
46
+ readonly present: Form;
47
+ readonly past: Form;
48
+ readonly failed: Form;
49
+ /** The roll-up's verb and counted noun; undefined for a kind the roll-up leaves out. */
50
+ readonly counted?: readonly [verb: string, noun: string];
51
+ }
52
+
53
+ /** The words of every kind (module header). */
54
+ export const KIND_WORDS: Readonly<Record<ToolKind, KindWords>> = {
55
+ file_read: { present: ["Reading", "Reading a file"], past: ["Read", "Read a file"], failed: ["Couldn't read", "Couldn't read a file"], counted: ["read", "file"] },
56
+ file_write: { present: ["Writing", "Writing a file"], past: ["Wrote", "Wrote a file"], failed: ["Couldn't write", "Couldn't write a file"], counted: ["wrote", "file"] },
57
+ file_edit: { present: ["Editing", "Editing a file"], past: ["Edited", "Edited a file"], failed: ["Couldn't edit", "Couldn't edit a file"], counted: ["edited", "file"] },
58
+ file_delete: {
59
+ present: ["Deleting", "Deleting a file"],
60
+ past: ["Deleted", "Deleted a file"],
61
+ failed: ["Couldn't delete", "Couldn't delete a file"],
62
+ counted: ["deleted", "file"],
63
+ },
64
+ shell: { present: ["Running a command", "Running a command"], past: ["Ran a command", "Ran a command"], failed: ["Command failed", "Command failed"], counted: ["ran", "command"] },
65
+ search: { present: ["Searching for", "Searching"], past: ["Searched for", "Searched"], failed: ["Couldn't search for", "Couldn't search"], counted: ["searched", "pattern"] },
66
+ list: {
67
+ present: ["Looking in", "Looking through files"],
68
+ past: ["Looked in", "Looked through files"],
69
+ failed: ["Couldn't look in", "Couldn't look through files"],
70
+ counted: ["looked through", "folder"],
71
+ },
72
+ fetch: { present: ["Reading", "Reading a page"], past: ["Read", "Read a page"], failed: ["Couldn't read", "Couldn't read a page"], counted: ["read", "page"] },
73
+ web_search: {
74
+ present: ["Searching the web for", "Searching the web"],
75
+ past: ["Searched the web for", "Searched the web"],
76
+ failed: ["Couldn't search the web for", "Couldn't search the web"],
77
+ counted: ["searched the web", "time"],
78
+ },
79
+ think: { present: ["Thinking", "Thinking"], past: ["Thought it through", "Thought it through"], failed: ["Thought it through", "Thought it through"] },
80
+ todo: { present: ["Planning", "Planning"], past: ["Updated the plan", "Updated the plan"], failed: ["Couldn't update the plan", "Couldn't update the plan"] },
81
+ subagent: {
82
+ present: ["A helper is working on", "A helper is working"],
83
+ past: ["A helper worked on", "A helper worked"],
84
+ failed: ["A helper couldn't finish", "A helper couldn't finish"],
85
+ },
86
+ mcp: { present: ["Using", "Using a tool"], past: ["Used", "Used a tool"], failed: ["Couldn't use", "Couldn't use a tool"], counted: ["used", "tool"] },
87
+ memory: { present: ["Remembering", "Remembering"], past: ["Remembered", "Remembered"], failed: ["Couldn't remember", "Couldn't remember"] },
88
+ background_stop: {
89
+ present: ["Stopping a command", "Stopping a command"],
90
+ past: ["Stopped a command", "Stopped a command"],
91
+ failed: ["Couldn't stop a command", "Couldn't stop a command"],
92
+ },
93
+ skill: {
94
+ present: ["Using the skill", "Using a skill"],
95
+ past: ["Used the skill", "Used a skill"],
96
+ failed: ["Couldn't use the skill", "Couldn't use a skill"],
97
+ counted: ["used", "skill"],
98
+ },
99
+ unknown: { present: ["Working", "Working"], past: ["Used a tool", "Used a tool"], failed: ["A tool failed", "A tool failed"], counted: ["used", "tool"] },
100
+ };
101
+
102
+ /** `form` with `target` after its verb, or alone when there is none. */
103
+ export function phraseOf(form: Form, target: string): string {
104
+ return target === "" ? form[1] : `${form[0]} ${target}`;
105
+ }
106
+
107
+ /** The longest target a phrase carries before it is cut. */
108
+ const TARGET_MAX = 48;
109
+
110
+ /** Names that search for files by name, not in their text. */
111
+ const FILE_NAME_SEARCHES: ReadonlySet<string> = new Set(["glob", "Glob", "find_files"]);
112
+
113
+ /** The input's text at `key`, or "". */
114
+ function textAt(tool: Pick<ToolUse, "input">, key: string): string {
115
+ const value = tool.input[key];
116
+ return typeof value === "string" ? value : "";
117
+ }
118
+
119
+ /** The path a file call names, from the fields the engines use. */
120
+ function pathOf(tool: Pick<ToolUse, "input">): string {
121
+ return textAt(tool, "path") || textAt(tool, "file_path") || textAt(tool, "notebook_path");
122
+ }
123
+
124
+ /** What a call acts on, in a few characters: a file's name, a search's pattern, a page's host, a subagent's task. */
125
+ export function targetOf(tool: Pick<ToolUse, "name" | "mcpServerName" | "input">): string {
126
+ const kind = resolveToolKind(tool);
127
+ switch (kind) {
128
+ case "file_read":
129
+ case "file_write":
130
+ case "file_edit":
131
+ case "file_delete":
132
+ return short(baseName(pathOf(tool)));
133
+ case "search":
134
+ return short(textAt(tool, "pattern") || textAt(tool, "query"));
135
+ case "fetch":
136
+ return short(hostOf(textAt(tool, "url")));
137
+ case "web_search":
138
+ return short(textAt(tool, "query"));
139
+ case "subagent":
140
+ return short(textAt(tool, "description"));
141
+ case "mcp":
142
+ return short(tool.name);
143
+ case "skill":
144
+ return short(textAt(tool, "skill") || textAt(tool, "name"));
145
+ case "list":
146
+ // The folder's last two segments ("src/billing"): its last alone
147
+ // ("billing") leaves a reader guessing which, and a whole absolute
148
+ // path crowds the line.
149
+ return short(folderWords(textAt(tool, "path")));
150
+ case "shell":
151
+ case "think":
152
+ case "todo":
153
+ case "memory":
154
+ case "background_stop":
155
+ case "unknown":
156
+ return "";
157
+ /* v8 ignore next -- @preserve: the exhaustiveness guard over ToolKind; resolveToolKind answers only the arms above */
158
+ default: {
159
+ const never: never = kind;
160
+ return never;
161
+ }
162
+ }
163
+ }
164
+
165
+ /**
166
+ * How `tool` stands: open, returned, failed (an error result, a denial, or a
167
+ * command that exited non-zero), or stopped before it returned. A background
168
+ * command's own end is its status line's to say, never the step's.
169
+ */
170
+ export function stepTense(tool: ToolUse): StepTense {
171
+ if (tool.state === "failed" || tool.state === "denied") return "failed";
172
+ // Waiting: worded as what it would do (stepPhrase), standing as open.
173
+ if (tool.state === "waiting") return "present";
174
+ if (tool.state === "stopped") return "stopped";
175
+ if (tool.result === undefined) return "present";
176
+ // An edit the Stigmer harness refused answers as a result, not an error
177
+ // ("Error: String not found in file"): nothing changed, so it failed.
178
+ if (resolveToolKind(tool) === "file_edit" && refusedEdit(tool.result.text)) return "failed";
179
+ if (resolveToolKind(tool) === "shell" && tool.background === undefined) {
180
+ const view = normalizeToolResult(tool);
181
+ if (view.type === "terminal" && view.exitCode !== undefined && view.exitCode !== 0) return "failed";
182
+ }
183
+ return "past";
184
+ }
185
+
186
+ /**
187
+ * `tool`'s line, in the tense it stands in (module header). A call that
188
+ * waits for a person's yes has done nothing yet: it reads as what the agent
189
+ * wants to do ("Wants to write rounding.ts").
190
+ */
191
+ export function stepPhrase(tool: ToolUse, options: StepPhraseOptions = {}): StepPhrase {
192
+ const phrase = stepPhraseByTense(tool);
193
+ // A write that made the file reads as what it did ("Created rounding.test.ts").
194
+ if (options.created === true && phrase.tense === "past" && resolveToolKind(tool) === "file_write") {
195
+ const wrote = KIND_WORDS.file_write.past;
196
+ const created = phrase.text === wrote[1] ? CREATED[1] : phrase.text.startsWith(`${wrote[0]} `) ? `${CREATED[0]}${phrase.text.slice(wrote[0].length)}` : phrase.text;
197
+ return { ...phrase, text: created };
198
+ }
199
+ if (tool.state !== "waiting" || !phrase.text.startsWith("Couldn't ")) return phrase;
200
+ return { ...phrase, text: `Wants to ${phrase.text.slice("Couldn't ".length)}` };
201
+ }
202
+
203
+ /** What a step's line may know beyond the call itself. */
204
+ export interface StepPhraseOptions {
205
+ /**
206
+ * The file a write wrote did not exist before its turn: the turn's file
207
+ * review says so (its change is `added`). Nothing in the call says it, so
208
+ * a session with no review reads "Wrote".
209
+ */
210
+ readonly created?: boolean;
211
+ }
212
+
213
+ /** A write that made its file, with a target and without one. */
214
+ const CREATED: Form = ["Created", "Created a file"];
215
+
216
+ // The first lines the engines answer a refused edit with: the Stigmer
217
+ // harness answers it as a result in both its backends' words, which the
218
+ // conformance suite's classifier keys the same way
219
+ // (test/conformance/src/benchmark/tool-call-facts.ts).
220
+ const EDIT_NOT_FOUND = /^(?:Error: )?String not found in file/;
221
+ const EDIT_NOT_UNIQUE = /has multiple occurrences|^(?:Error: )?Multiple occurrences found in/;
222
+ const NO_SUCH_FILE = /no such file|ENOENT|file not found|does not exist/i;
223
+
224
+ /** The first line of an answer that reads, trimmed; "" when it has none. */
225
+ function firstLine(text: string): string {
226
+ return (text.split("\n").find((line) => line.trim() !== "") ?? "").trim();
227
+ }
228
+
229
+ /** Whether an edit's answer says it changed nothing. */
230
+ function refusedEdit(text: string): boolean {
231
+ const first = firstLine(text);
232
+ return EDIT_NOT_FOUND.test(first) || EDIT_NOT_UNIQUE.test(first);
233
+ }
234
+
235
+ /**
236
+ * Why a step failed, as a sentence a person reads, from its answer. Only the
237
+ * answer's first line is the engine's reason: the runner appends recovery
238
+ * hints for the model after it (`enrichErrorMessage`), which are never shown.
239
+ * A reason the engines are known to give reads in plain words ("The text to
240
+ * replace wasn't in the file, so nothing changed."); any other is the
241
+ * engine's own line, without an "Error:" label, as a sentence.
242
+ */
243
+ export function failureWords(text: string): string {
244
+ const first = firstLine(text);
245
+ if (EDIT_NOT_FOUND.test(first)) return "The text to replace wasn't in the file, so nothing changed.";
246
+ if (EDIT_NOT_UNIQUE.test(first)) return "The text to replace was in the file more than once, so nothing changed.";
247
+ if (NO_SUCH_FILE.test(first)) return "The file wasn't there.";
248
+ const reason = first.replace(/^error:\s*/i, "");
249
+ return reason === "" ? "" : reason.charAt(0).toUpperCase() + reason.slice(1);
250
+ }
251
+
252
+ /**
253
+ * How many a search found, as its step says it: "4 files" for a search by
254
+ * name, "2 matches", and "2 matches in 2 files" once its matches name more
255
+ * than one file. Other views count nothing ("").
256
+ */
257
+ export function searchCountWords(view: ToolResultView): string {
258
+ if (view.type !== "search") return "";
259
+ if (view.kind === "files") return `${view.count} ${view.count === 1 ? "file" : "files"}`;
260
+ const matches = `${view.count} ${view.count === 1 ? "match" : "matches"}`;
261
+ const files = new Set(view.matches.flatMap((match) => (match.file === undefined ? [] : [match.file]))).size;
262
+ return files > 1 ? `${matches} in ${files} files` : matches;
263
+ }
264
+
265
+ /** The lines a step shows of a file, as words: "Lines 14–17 of 88", or "Lines 14–17" when the length is not known. */
266
+ export function lineRangeWords(range: FileLineRange): string {
267
+ const span = range.start === range.end ? `Line ${range.start}` : `Lines ${range.start}–${range.end}`;
268
+ return range.total === undefined ? span : `${span} of ${range.total}`;
269
+ }
270
+
271
+ function stepPhraseByTense(tool: ToolUse): StepPhrase {
272
+ const tense = stepTense(tool);
273
+ // A step its turn stopped did not get done: it reads as one that couldn't.
274
+ // A waiting one takes the same form, which stepPhrase turns into a want.
275
+ const form: Exclude<StepTense, "stopped"> = tense === "stopped" || tool.state === "waiting" ? "failed" : tense;
276
+ const kind = resolveToolKind(tool);
277
+ const app = tool.mcpServerName;
278
+ if (kind === "mcp" || kind === "unknown") return { text: humanizeToolName(tool.name), tense, folder: "", app };
279
+ if (kind === "shell") {
280
+ const description = textAt(tool, "description").replace(/\s+/g, " ").trim();
281
+ const words = tool.state === "waiting" ? "Wants to run a command" : phraseOf(KIND_WORDS.shell[form], "");
282
+ return { text: description === "" ? words : short(description), tense, folder: "", app };
283
+ }
284
+ if (kind === "search" && FILE_NAME_SEARCHES.has(tool.name)) {
285
+ const pattern = short(textAt(tool, "pattern"));
286
+ const words: Readonly<Record<Exclude<StepTense, "stopped">, Form>> = {
287
+ present: ["Finding files matching", "Finding files"],
288
+ past: ["Found files matching", "Found files"],
289
+ failed: ["Couldn't find files matching", "Couldn't find files"],
290
+ };
291
+ return { text: phraseOf(words[form], pattern), tense, folder: "", app };
292
+ }
293
+ const target = targetOf(tool);
294
+ const text = phraseOf(KIND_WORDS[kind][form], target);
295
+ if (kind === "search") {
296
+ const where = target !== "" ? short(trimSeparators(textAt(tool, "path"))) : "";
297
+ // At work, a search has no counts yet: where it looks is its second line,
298
+ // as a file step's folder is ("Searching for round(", then "src/billing").
299
+ // Done, its counts take the second line and the folder joins its words.
300
+ if (form === "present") return { text, tense, folder: where, app };
301
+ return { text: where !== "" ? `${text} in ${where}` : text, tense, folder: "", app };
302
+ }
303
+ const isFile = kind === "file_read" || kind === "file_write" || kind === "file_edit" || kind === "file_delete";
304
+ return { text, tense, folder: isFile && target !== "" ? short(folderOf(pathOf(tool))) : "", app };
305
+ }
306
+
307
+ /**
308
+ * A tool's name as words, in sentence case: `create_issue`, `createIssue`
309
+ * and `Create-Issue` all read "Create issue". A name with nothing to read
310
+ * reads "A tool".
311
+ */
312
+ export function humanizeToolName(name: string): string {
313
+ const words = name
314
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
315
+ .split(/[\s_\-.:/]+/)
316
+ .filter((word) => word !== "")
317
+ .map((word) => word.toLowerCase());
318
+ if (words.length === 0) return "A tool";
319
+ const text = words.join(" ");
320
+ return short(text.charAt(0).toUpperCase() + text.slice(1));
321
+ }
322
+
323
+ // The path is the model's, so the trailing separators are trimmed by a loop:
324
+ // a regular expression like /[\\/]+$/ backtracks quadratically on a long run
325
+ // of them, and the activity line reads this every second.
326
+ function trimSeparators(path: string): string {
327
+ let end = path.length;
328
+ while (end > 0 && (path[end - 1] === "/" || path[end - 1] === "\\")) end -= 1;
329
+ return path.slice(0, end);
330
+ }
331
+
332
+ export function baseName(path: string): string {
333
+ const trimmed = trimSeparators(path);
334
+ return trimmed.slice(Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\")) + 1);
335
+ }
336
+
337
+ /** The folder a path sits in, without its trailing separator; "" at the root or for a bare name. */
338
+ function folderOf(path: string): string {
339
+ const trimmed = trimSeparators(path);
340
+ const at = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
341
+ return at <= 0 ? "" : trimmed.slice(0, at);
342
+ }
343
+
344
+ function hostOf(url: string): string {
345
+ try {
346
+ return new URL(url).host;
347
+ } catch {
348
+ return "";
349
+ }
350
+ }
351
+
352
+ /** A folder as a step names it: its last two segments, "/workspace/app/src/billing" read as "src/billing". */
353
+ function folderWords(path: string): string {
354
+ return trimSeparators(path).split(/[\\/]/).filter((segment) => segment !== "").slice(-2).join("/");
355
+ }
356
+
357
+ export function short(value: string): string {
358
+ const flat = value.replace(/\s+/g, " ").trim();
359
+ return flat.length <= TARGET_MAX ? flat : `${flat.slice(0, TARGET_MAX - 1)}…`;
360
+ }