@prefactor/pi 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.
Files changed (56) hide show
  1. package/README.md +226 -2
  2. package/dist/commands.d.ts +32 -0
  3. package/dist/commands.d.ts.map +1 -0
  4. package/dist/commands.js +395 -0
  5. package/dist/commands.js.map +1 -0
  6. package/dist/credentials.d.ts +67 -0
  7. package/dist/credentials.d.ts.map +1 -0
  8. package/dist/credentials.js +120 -0
  9. package/dist/credentials.js.map +1 -0
  10. package/dist/data-risk.d.ts +11 -0
  11. package/dist/data-risk.d.ts.map +1 -0
  12. package/dist/data-risk.js +125 -0
  13. package/dist/data-risk.js.map +1 -0
  14. package/dist/device-login.d.ts +45 -0
  15. package/dist/device-login.d.ts.map +1 -0
  16. package/dist/device-login.js +163 -0
  17. package/dist/device-login.js.map +1 -0
  18. package/dist/extension.d.ts +44 -0
  19. package/dist/extension.d.ts.map +1 -0
  20. package/dist/extension.js +204 -0
  21. package/dist/extension.js.map +1 -0
  22. package/dist/index.cjs +1805 -0
  23. package/dist/index.cjs.map +22 -0
  24. package/dist/index.d.ts +19 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +1772 -0
  27. package/dist/index.js.map +22 -0
  28. package/dist/prefactor-api.d.ts +38 -0
  29. package/dist/prefactor-api.d.ts.map +1 -0
  30. package/dist/prefactor-api.js +63 -0
  31. package/dist/prefactor-api.js.map +1 -0
  32. package/dist/prefactor-session.d.ts +126 -0
  33. package/dist/prefactor-session.d.ts.map +1 -0
  34. package/dist/prefactor-session.js +274 -0
  35. package/dist/prefactor-session.js.map +1 -0
  36. package/dist/recorder.d.ts +54 -0
  37. package/dist/recorder.d.ts.map +1 -0
  38. package/dist/recorder.js +70 -0
  39. package/dist/recorder.js.map +1 -0
  40. package/dist/schema.d.ts +54 -0
  41. package/dist/schema.d.ts.map +1 -0
  42. package/dist/schema.js +220 -0
  43. package/dist/schema.js.map +1 -0
  44. package/dist/session-tracer.d.ts +144 -0
  45. package/dist/session-tracer.d.ts.map +1 -0
  46. package/dist/session-tracer.js +390 -0
  47. package/dist/session-tracer.js.map +1 -0
  48. package/dist/tool-definitions.d.ts +17 -0
  49. package/dist/tool-definitions.d.ts.map +1 -0
  50. package/dist/tool-definitions.js +69 -0
  51. package/dist/tool-definitions.js.map +1 -0
  52. package/dist/version.d.ts +3 -0
  53. package/dist/version.d.ts.map +1 -0
  54. package/dist/version.js +4 -0
  55. package/dist/version.js.map +1 -0
  56. package/package.json +54 -4
package/README.md CHANGED
@@ -1,3 +1,227 @@
1
- # Temporary Holding Version
1
+ # @prefactor/pi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [pi](https://pi.dev) extension that records pi sessions in Prefactor. Each pi session becomes one Prefactor agent instance, which Prefactor shows as a conversation of user turns, assistant turns, LLM calls and tool calls.
4
+
5
+ > **Sensitive data:** the extension records prompts, completions and tool results as they are, without redaction. Coding sessions often contain source code, credentials and other secrets, so do not use it for sessions that handle data you cannot send to Prefactor.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pi install npm:@prefactor/pi
11
+ ```
12
+
13
+ To try it for one run without adding it to your settings:
14
+
15
+ ```bash
16
+ pi -e npm:@prefactor/pi
17
+ ```
18
+
19
+ ## Connect pi to Prefactor
20
+
21
+ Run this inside pi:
22
+
23
+ ```text
24
+ /prefactor setup
25
+ ```
26
+
27
+ It signs you in through Prefactor in the browser. pi opens the sign-in page and shows the link, which you can also open yourself, or on another device when pi runs over SSH or in a container, and the code to approve there. You then create an agent for pi, named "pi" unless you choose another name, or pick one of your account's existing agents, and choose the environment when the agent has more than one deployment. Setup creates an agent-deployment token for that agent and environment, checks it, and saves it to `~/.pi/agent/prefactor.json` with file mode `0600`.
28
+
29
+ The account token from the sign-in is kept in memory only. Setup revokes it once the deployment token is saved, or when setup stops early. If revoking fails, setup keeps the deployment token and tells you to revoke the account token under Account settings in Prefactor.
30
+
31
+ If the server does not offer browser sign-in, or you choose to, setup asks you to paste an agent-deployment token instead. The token is visible on screen while you paste it.
32
+
33
+ | Command | Does |
34
+ | --- | --- |
35
+ | `/prefactor setup` | Connects pi to Prefactor. Asks first when credentials already exist. |
36
+ | `/prefactor status` | Shows where the credentials come from, the API URL, the account and agent, and whether the last request to Prefactor succeeded. |
37
+ | `/prefactor logout` | Deletes the credentials file. Credentials from code or the environment are not affected. |
38
+
39
+ The commands need dialogs, so they work in interactive and RPC modes. In print and JSON modes, use the environment variables below.
40
+
41
+ ## Credentials
42
+
43
+ The extension sends spans with a Prefactor agent-deployment token. When a session starts, it reads credentials from the first of these sources that supplies a token:
44
+
45
+ 1. Options passed to `prefactorExtension()` in code.
46
+ 2. The environment variables `PREFACTOR_API_URL`, `PREFACTOR_API_TOKEN` and `PREFACTOR_AGENT_ID`.
47
+ 3. The credentials file written by `/prefactor setup`, `~/.pi/agent/prefactor.json`. It follows pi's `PI_CODING_AGENT_DIR` setting when that is set.
48
+
49
+ The agent id comes from the same source as the token. When that source has no agent id, the extension reads it from the token with `GET /api/v1/ping`. The API URL comes from the token's source or a later one, and defaults to `https://app.prefactorai.com`.
50
+
51
+ The credentials file holds `api_url`, `api_token` (the deployment token), `agent_id`, `environment_id`, `account_id` and `created_at`. Setup with browser sign-in also saves `agent_name` and `account_name`. A pasted deployment token cannot read those names from Prefactor, so they are left out, and `/prefactor status` shows the agent and account ids instead. The file never holds an account token.
52
+
53
+ When no token is found, the extension records nothing and tells you once how to set Prefactor up, so pi keeps working. In interactive and RPC modes the notice appears in pi. In print and JSON modes it is written to stderr.
54
+
55
+ ## Agents built on pi's SDK
56
+
57
+ Agents built with `@earendil-works/pi-coding-agent` load the same extension in code through `extensionFactories`, and each session is recorded as one agent instance. Install the package alongside pi:
58
+
59
+ ```bash
60
+ npm install @prefactor/pi @earendil-works/pi-coding-agent
61
+ ```
62
+
63
+ ```typescript
64
+ import {
65
+ type CreateAgentSessionRuntimeFactory,
66
+ createAgentSessionFromServices,
67
+ createAgentSessionRuntime,
68
+ createAgentSessionServices,
69
+ getAgentDir,
70
+ SessionManager,
71
+ } from '@earendil-works/pi-coding-agent';
72
+ import { prefactorExtension } from '@prefactor/pi';
73
+
74
+ const createRuntime: CreateAgentSessionRuntimeFactory = async ({ cwd, sessionManager, sessionStartEvent }) => {
75
+ const services = await createAgentSessionServices({
76
+ cwd,
77
+ resourceLoaderOptions: {
78
+ extensionFactories: [
79
+ prefactorExtension({
80
+ apiUrl: 'https://app.prefactorai.com',
81
+ apiToken: process.env.MY_PREFACTOR_TOKEN,
82
+ agentVersion: '2.3.0',
83
+ }),
84
+ ],
85
+ },
86
+ });
87
+ return {
88
+ ...(await createAgentSessionFromServices({ services, sessionManager, sessionStartEvent })),
89
+ services,
90
+ diagnostics: services.diagnostics,
91
+ };
92
+ };
93
+
94
+ const runtime = await createAgentSessionRuntime(createRuntime, {
95
+ cwd: process.cwd(),
96
+ agentDir: getAgentDir(),
97
+ sessionManager: SessionManager.inMemory(),
98
+ });
99
+
100
+ try {
101
+ await runtime.session.bindExtensions({});
102
+ await runtime.session.prompt('What files are in the current directory?');
103
+ } finally {
104
+ await runtime.dispose();
105
+ }
106
+ ```
107
+
108
+ `prefactorExtension()` takes these options. Each credential falls back to its environment variable, then to the credentials file, as described under [Credentials](#credentials).
109
+
110
+ | Option | Meaning |
111
+ | --- | --- |
112
+ | `apiUrl` | Prefactor API URL |
113
+ | `apiToken` | Agent-deployment token |
114
+ | `agentId` | Prefactor agent id, read from the token when omitted |
115
+ | `agentVersion` | Identifies the agent version recorded for each session. Defaults to the version of the pi framework. Prefactor identifies agent versions by this value alone; the extension sends no name or description for them. |
116
+ | `spanTypeSchemas` | Span types for the agent's own spans, added to the schema version the extension registers. They cannot redefine `pi:session` or the `$agent:*` span types. |
117
+ | `qualitySchemas` | Quality schemas for quality recorded on the session's agent instance |
118
+ | `alertSchemas` | Alert schemas for alerts raised on the session's agent instance |
119
+ | `toolSchemas` | Span type details by tool name: `title`, `description`, `template`, `params_schema` (the tool's arguments), `result_schema` (the structured `details` the tool returns, recorded as `result.details`) and `data_risk`. The tool keeps its `$agent:tool:<name>` span type, so Prefactor still shows it as a tool call, and a tool listed here gets that span type even when it is added after the session starts. |
120
+ | `externalIdentifier` | External identifier of each session's agent instance, such as the id of the CI run that ran the session: a string, or a function `(ctx) => string \| undefined` called at each session start. See [External identifiers](#external-identifiers). |
121
+ | `onSessionStart` | Called with the session's recorder when the extension starts recording a session. It may be async; pi does not wait for it, and a rejection is logged. See [Adding to the record](#adding-to-the-record). |
122
+
123
+ The session lifecycle depends on two calls:
124
+
125
+ - `session.bindExtensions()` emits `session_start`, which starts the agent instance. Nothing is recorded until it is called.
126
+ - `AgentSessionRuntime.dispose()` emits `session_shutdown`, which finishes the agent instance after the remaining spans are sent. `AgentSession.dispose()` on its own does not emit `session_shutdown`, so with `createAgentSession()` the agent instance stays active in Prefactor. Use `AgentSessionRuntime` as above when the instance should be finished.
127
+
128
+ The `pi` command always records pi's release version, because it loads the extension without options.
129
+
130
+ ### Adding to the record
131
+
132
+ Agents that run their own steps around pi can add spans, quality and alerts to the session's agent instance through the recorder that `onSessionStart` receives. Declare the span types, quality schemas and alert schemas in the options first, because Prefactor accepts only those declared in the agent's schema version.
133
+
134
+ ```typescript
135
+ import { type PrefactorRecorder, prefactorExtension } from '@prefactor/pi';
136
+
137
+ let recorder: PrefactorRecorder | undefined;
138
+
139
+ const extension = prefactorExtension({
140
+ agentVersion: '2.3.0',
141
+ spanTypeSchemas: [
142
+ {
143
+ name: 'signal:poll_source',
144
+ template: 'Poll {{ source }}',
145
+ params_schema: { type: 'object', properties: { source: { type: 'string' } } },
146
+ result_schema: { type: 'object', properties: { items: { type: 'integer' } } },
147
+ },
148
+ ],
149
+ qualitySchemas: [
150
+ { name: 'signal:run_quality', schema: { type: 'object', properties: { sources_failed: { type: 'integer' } } } },
151
+ ],
152
+ alertSchemas: [
153
+ { name: 'signal:monitor_broken', schema: { type: 'object', properties: { reason: { type: 'string' } } } },
154
+ ],
155
+ onSessionStart: (sessionRecorder) => {
156
+ recorder = sessionRecorder;
157
+ },
158
+ });
159
+
160
+ // Later, while the session runs:
161
+ const poll = recorder?.startSpan({ schemaName: 'signal:poll_source', payload: { source: 'reddit' } });
162
+ poll?.complete({ items: 12 });
163
+ recorder?.recordQuality('signal:run_quality', { sources_failed: 0 });
164
+ recorder?.raiseAlert('signal:monitor_broken', 'error', { reason: 'every source failed' });
165
+ ```
166
+
167
+ | Recorder method | Does |
168
+ | --- | --- |
169
+ | `startSpan({ schemaName, payload, parent })` | Starts a span and returns it; finish it with `complete(result)` or `fail(result)`. It nests under `parent`, which is another span from the recorder or `{ toolCallId }` for a running tool call (for example, from inside a custom tool's `execute`). Without a parent, it nests under the open assistant turn, or under `pi:session` between runs. Spans still open at shutdown are cancelled. |
170
+ | `recordQuality(name, payload)` | Records quality on the agent instance. `null` removes the value recorded for that name. |
171
+ | `raiseAlert(name, severity, payload)` | Raises an alert on the agent instance. Severity is `critical`, `error`, `warning` or `info`. The agent-deployment token can raise alerts, so no other token is needed. |
172
+ | `setFinishStatus(status)` | Sets the status the agent instance finishes with at session shutdown: `complete`, `failed` or `cancelled`. The last call wins. Without a call, the instance finishes as `complete`. |
173
+
174
+ The recorder's methods never throw and never wait for the network. Failures are logged. After the session shuts down, they record nothing. `onSessionStart` is not called when no Prefactor token is found.
175
+
176
+ ### External identifiers
177
+
178
+ Prefactor requires an agent instance's external identifier to be unique per agent. A session whose identifier the agent has already used fails to register, and nothing is recorded for it; pi keeps running and shows that Prefactor could not record the session.
179
+
180
+ A plain string therefore suits a process that runs one session, such as one CI job. When a process runs several sessions, pass a function, which is called at each session start with pi's extension context and can return a different identifier for each session, or `undefined` for none:
181
+
182
+ ```typescript
183
+ prefactorExtension({
184
+ externalIdentifier: (ctx) => `${process.env.GITHUB_RUN_ID}:${ctx.sessionManager.getSessionId()}`,
185
+ });
186
+ ```
187
+
188
+ A function that throws is logged, and the session registers without an external identifier.
189
+
190
+ ## What gets recorded
191
+
192
+ pi's work is recorded with Prefactor's canonical agent span types, the ones Prefactor's hosted agents use, so each session opens in Prefactor's conversation view.
193
+
194
+ | Span type | Covers | Recorded |
195
+ | --- | --- | --- |
196
+ | `pi:session` | One pi session, the root of every other span | Session id, working directory, mode, start reason and model; shutdown reason |
197
+ | `$agent:system_message` | The system prompt | The prompt in effect when a run starts, recorded when it differs from the last one recorded |
198
+ | `$agent:user_turn` | One user message | The number of the turn in the session |
199
+ | `$agent:user_message` | A prompt, steering message or follow-up message, in its user turn | The message text |
200
+ | `$agent:assistant_turn` | The assistant's work after a user turn | Stop reason of the last response and the token usage summed over the turn's responses |
201
+ | `$agent:llm_call` | One assistant response, in its assistant turn | Provider, model and API; response id and model, stop reason, token usage (including cache read and cache write tokens), cost and times, or the error |
202
+ | `$agent:assistant_thinking`, `$agent:assistant_message` | Each thinking and text block of a response, in its assistant turn | The block's text |
203
+ | `$agent:tool:<name>` | One tool execution, in its assistant turn | Tool call id and arguments; the result content and details, or the error |
204
+
205
+ Each tool pi has when the session starts gets its own `$agent:tool:<name>` span type. A tool added later, for example by an extension during the session, is recorded as `$agent:tool:pi:other` with its name in `tool_name`. A tool call made by another tool, such as a codemode script, is a child of that tool's span.
206
+
207
+ The assistant turn finishes when the run ends, or when a steering message starts the next user turn while the run continues.
208
+
209
+ The agent version is pi's release version, or `agentVersion` for agents built on pi's SDK. The working directory on each session lets you tell apart sessions from different repositories that report to the same agent.
210
+
211
+ Long strings are truncated to `PREFACTOR_MAX_INPUT_LENGTH` and `PREFACTOR_MAX_OUTPUT_LENGTH` characters (10,000 by default).
212
+
213
+ ## Shutdown and Ctrl+C
214
+
215
+ The session appears in Prefactor as soon as it starts. Each span is sent as soon as it starts or finishes, and the agent instance is finished when pi runs `session_shutdown`.
216
+
217
+ Pressing Ctrl+C in print, JSON or RPC mode ends pi without running `session_shutdown`. Spans that had already finished are recorded. The open assistant turn, the session span and the agent instance stay active in Prefactor.
218
+
219
+ ## Examples
220
+
221
+ - [`examples/pi/print-mode.ts`](../../examples/pi/print-mode.ts) runs `pi` once in print mode with the extension loaded from this repository.
222
+ - [`examples/pi/sdk-agent.ts`](../../examples/pi/sdk-agent.ts) builds an agent on pi's SDK and records its session.
223
+
224
+ ## Requirements
225
+
226
+ - Node.js >= 22.19.0
227
+ - pi (`@earendil-works/pi-coding-agent`) 0.99.0 or later
@@ -0,0 +1,32 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
2
+ import type { HttpRequester } from '@prefactor/core';
3
+ import { type ResolvedCredentials } from './credentials.js';
4
+ import { type DeviceLoginDeps } from './device-login.js';
5
+ import type { StartState } from './prefactor-session.js';
6
+ export declare const DEFAULT_AGENT_NAME = "pi";
7
+ /** What the commands need from the running extension. */
8
+ export interface PrefactorCommandHost {
9
+ /** Resolves the credentials the extension would use now. */
10
+ resolveCredentials(): Promise<ResolvedCredentials | undefined>;
11
+ /** The credentials and last request error of the session being recorded, if any. */
12
+ getRecording(): {
13
+ credentials: ResolvedCredentials;
14
+ lastError: unknown;
15
+ startState: StartState;
16
+ } | null;
17
+ /**
18
+ * Starts recording the current session, when it is not recorded yet or its agent instance
19
+ * failed to start.
20
+ */
21
+ startRecording(ctx: ExtensionCommandContext): Promise<void>;
22
+ /** Creates an HTTP requester for an API URL and token. */
23
+ createClient(apiUrl: string, apiToken: string): HttpRequester;
24
+ clientVersion: string;
25
+ loginDeps?: DeviceLoginDeps;
26
+ openBrowser?: (url: string) => void;
27
+ }
28
+ /**
29
+ * Registers `/prefactor setup`, `/prefactor status` and `/prefactor logout`.
30
+ */
31
+ export declare function registerPrefactorCommand(pi: ExtensionAPI, host: PrefactorCommandHost): void;
32
+ //# sourceMappingURL=commands.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE7F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAKL,KAAK,mBAAmB,EAGzB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAGL,KAAK,eAAe,EAKrB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,eAAO,MAAM,kBAAkB,OAAO,CAAC;AAYvC,yDAAyD;AACzD,MAAM,WAAW,oBAAoB;IACnC,4DAA4D;IAC5D,kBAAkB,IAAI,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAAC;IAC/D,oFAAoF;IACpF,YAAY,IAAI;QACd,WAAW,EAAE,mBAAmB,CAAC;QACjC,SAAS,EAAE,OAAO,CAAC;QACnB,UAAU,EAAE,UAAU,CAAC;KACxB,GAAG,IAAI,CAAC;IACT;;;OAGG;IACH,cAAc,CAAC,GAAG,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5D,0DAA0D;IAC1D,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,aAAa,CAAC;IAC9D,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CACrC;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,oBAAoB,GAAG,IAAI,CAyC3F"}
@@ -0,0 +1,395 @@
1
+ import { Container, Input, SelectList, Text } from '@earendil-works/pi-tui';
2
+ import { DEFAULT_API_URL, deleteCredentialsFile, getCredentialsFilePath, readCredentialsFile, writeCredentialsFile, } from './credentials.js';
3
+ import { LoginCancelledError, openBrowser, pollForDeviceGrant, startDeviceLogin, } from './device-login.js';
4
+ import { PrefactorApi } from './prefactor-api.js';
5
+ export const DEFAULT_AGENT_NAME = 'pi';
6
+ const DEFAULT_AGENT_DESCRIPTION = 'pi coding agent sessions';
7
+ const DEPLOYMENT_TOKEN_TYPE = 'api_session_agent_deployment_scope';
8
+ const LOGIN_WIDGET = 'prefactor-login';
9
+ const SUBCOMMANDS = ['setup', 'status', 'logout'];
10
+ const SOURCE_LABELS = {
11
+ options: 'extension options in code',
12
+ environment: 'PREFACTOR_* environment variables',
13
+ file: 'credentials file',
14
+ };
15
+ /**
16
+ * Registers `/prefactor setup`, `/prefactor status` and `/prefactor logout`.
17
+ */
18
+ export function registerPrefactorCommand(pi, host) {
19
+ pi.registerCommand('prefactor', {
20
+ description: 'Connect pi to Prefactor: setup, status or logout',
21
+ getArgumentCompletions: (prefix) => {
22
+ const items = SUBCOMMANDS.filter((name) => name.startsWith(prefix.trim())).map((name) => ({
23
+ value: name,
24
+ label: name,
25
+ }));
26
+ return items.length > 0 ? items : null;
27
+ },
28
+ handler: async (args, ctx) => {
29
+ const subcommand = args.trim().split(/\s+/)[0] || 'status';
30
+ if (!ctx.hasUI) {
31
+ process.stderr.write('/prefactor needs interactive or RPC mode. In print and JSON modes, set PREFACTOR_API_URL, PREFACTOR_API_TOKEN and PREFACTOR_AGENT_ID.\n');
32
+ return;
33
+ }
34
+ try {
35
+ if (subcommand === 'setup') {
36
+ await setup(ctx, host);
37
+ }
38
+ else if (subcommand === 'status') {
39
+ await status(ctx, host);
40
+ }
41
+ else if (subcommand === 'logout') {
42
+ await logout(ctx, host);
43
+ }
44
+ else {
45
+ ctx.ui.notify(`Unknown subcommand "${subcommand}". Use setup, status or logout.`, 'error');
46
+ }
47
+ }
48
+ catch (error) {
49
+ if (error instanceof LoginCancelledError) {
50
+ ctx.ui.notify('Prefactor setup cancelled. Nothing was saved.', 'info');
51
+ return;
52
+ }
53
+ ctx.ui.notify(`Prefactor ${subcommand} failed: ${describe(error)}`, 'error');
54
+ }
55
+ },
56
+ });
57
+ }
58
+ async function setup(ctx, host) {
59
+ const current = await host.resolveCredentials();
60
+ if (current) {
61
+ const replace = await ctx.ui.confirm('Replace Prefactor credentials?', `pi already has Prefactor credentials from the ${SOURCE_LABELS[current.source]}. Set up new credentials?`);
62
+ if (!replace) {
63
+ return;
64
+ }
65
+ }
66
+ const file = await readCredentialsFile();
67
+ const apiUrl = process.env.PREFACTOR_API_URL || file?.api_url || DEFAULT_API_URL;
68
+ const method = await ctx.ui.select('Connect pi to Prefactor', [
69
+ 'Sign in with your browser',
70
+ 'Paste an agent-deployment token',
71
+ ]);
72
+ if (method === undefined) {
73
+ return;
74
+ }
75
+ const saved = method === 'Sign in with your browser'
76
+ ? await setupWithBrowser(ctx, host, apiUrl)
77
+ : await setupWithPastedToken(ctx, host, apiUrl);
78
+ if (!saved) {
79
+ return;
80
+ }
81
+ const active = await host.resolveCredentials();
82
+ if (active && active.source !== 'file') {
83
+ ctx.ui.notify(`Saved, but the ${SOURCE_LABELS[active.source]} take precedence over the credentials file.`, 'warning');
84
+ return;
85
+ }
86
+ await host.startRecording(ctx);
87
+ const recording = host.getRecording();
88
+ if (active && recording && recording.credentials.apiToken !== active.apiToken) {
89
+ ctx.ui.notify(recording.startState === 'pending'
90
+ ? 'This session keeps the Prefactor recording it is starting, and switches to the new credentials only if that recording fails to start. New sessions use the new credentials.'
91
+ : `This session keeps recording to ${recording.credentials.apiUrl}, agent ${recording.credentials.agentId ?? '(read from its token)'}. New sessions use the new credentials.`, 'info');
92
+ }
93
+ }
94
+ async function setupWithBrowser(ctx, host, apiUrl) {
95
+ const login = await startDeviceLogin(apiUrl, host.clientVersion, host.loginDeps);
96
+ if (login === 'unsupported') {
97
+ ctx.ui.notify(`${apiUrl} does not offer browser sign-in. Paste a token instead.`, 'warning');
98
+ return setupWithPastedToken(ctx, host, apiUrl);
99
+ }
100
+ const grant = await waitForApproval(ctx, host, apiUrl, login);
101
+ const accountApi = new PrefactorApi(host.createClient(apiUrl, grant.access_token));
102
+ try {
103
+ return await createDeploymentCredentials(ctx, host, apiUrl, grant, accountApi);
104
+ }
105
+ finally {
106
+ await revokeAccountToken(ctx, accountApi);
107
+ }
108
+ }
109
+ /**
110
+ * Shows the code and link in pi and polls until the sign-in is approved. The user can cancel from
111
+ * a dialog while pi waits. Interactive pi shows the link as a clickable widget; RPC clients
112
+ * receive it as a plain widget line.
113
+ */
114
+ async function waitForApproval(ctx, host, apiUrl, login) {
115
+ // pi's RPC mode sends only string-array widgets to the client and drops component factories.
116
+ if (ctx.mode === 'tui') {
117
+ ctx.ui.setWidget(LOGIN_WIDGET, (_tui, theme) => loginWidget(theme, login));
118
+ }
119
+ else {
120
+ ctx.ui.setWidget(LOGIN_WIDGET, [login.verification_uri_complete]);
121
+ }
122
+ (host.openBrowser ?? openBrowser)(login.verification_uri_complete);
123
+ const polling = new AbortController();
124
+ const dialog = new AbortController();
125
+ void ctx.ui
126
+ .select(`Approve code ${login.user_code} in your browser`, ['Cancel sign-in'], {
127
+ signal: dialog.signal,
128
+ })
129
+ .then(() => {
130
+ if (!dialog.signal.aborted) {
131
+ polling.abort();
132
+ }
133
+ });
134
+ try {
135
+ return await pollForDeviceGrant(apiUrl, login, polling.signal, host.loginDeps);
136
+ }
137
+ finally {
138
+ dialog.abort();
139
+ ctx.ui.setWidget(LOGIN_WIDGET, undefined);
140
+ }
141
+ }
142
+ /**
143
+ * The sign-in widget: the full link, broken at the terminal width. Each line is its own complete
144
+ * OSC 8 hyperlink to the full link, so it is clickable wherever the terminal wraps it, and no line
145
+ * is wider than the terminal.
146
+ */
147
+ function loginWidget(theme, login) {
148
+ const url = login.verification_uri_complete;
149
+ return {
150
+ render(width) {
151
+ return breakAtWidth(url, width).map((line) => theme.fg('mdLink', hyperlink(url, line)));
152
+ },
153
+ invalidate() { },
154
+ };
155
+ }
156
+ /** Wraps text in an OSC 8 hyperlink, which terminals that support it make clickable. */
157
+ function hyperlink(url, text) {
158
+ return `\x1b]8;;${url}\x1b\\${text}\x1b]8;;\x1b\\`;
159
+ }
160
+ /** Breaks plain single-width text, such as a URL, into lines of at most `width` columns. */
161
+ function breakAtWidth(text, width) {
162
+ const chars = [...text];
163
+ const step = Math.max(1, width);
164
+ const lines = [];
165
+ for (let start = 0; start < chars.length; start += step) {
166
+ lines.push(chars.slice(start, start + step).join(''));
167
+ }
168
+ return lines;
169
+ }
170
+ async function createDeploymentCredentials(ctx, host, apiUrl, grant, accountApi) {
171
+ if (!grant.account_id) {
172
+ throw new Error('The sign-in did not return an account id.');
173
+ }
174
+ const agent = await chooseAgent(ctx, accountApi);
175
+ if (!agent) {
176
+ return false;
177
+ }
178
+ const environmentId = await chooseEnvironment(ctx, accountApi, agent.id, grant.account_id);
179
+ if (!environmentId) {
180
+ return false;
181
+ }
182
+ const token = await accountApi.createDeploymentToken(agent.id, environmentId);
183
+ await checkDeploymentToken(host, apiUrl, token, agent.id);
184
+ await writeCredentialsFile({
185
+ api_url: apiUrl,
186
+ api_token: token,
187
+ agent_id: agent.id,
188
+ agent_name: agent.name,
189
+ environment_id: environmentId,
190
+ account_id: grant.account_id,
191
+ ...(grant.account_name ? { account_name: grant.account_name } : {}),
192
+ created_at: new Date().toISOString(),
193
+ });
194
+ ctx.ui.notify(`Connected pi to the Prefactor agent "${agent.name}"${grant.account_name ? ` in ${grant.account_name}` : ''}.`, 'info');
195
+ return true;
196
+ }
197
+ const CREATE_AGENT = 'Create a new agent for pi';
198
+ const USE_EXISTING_AGENT = 'Use an existing agent';
199
+ /**
200
+ * Chooses the agent pi reports to: a new agent, named and described by the user, or an existing
201
+ * one. Returns undefined when the user cancels at any step.
202
+ */
203
+ async function chooseAgent(ctx, api) {
204
+ const agents = await api.listAgents();
205
+ const choice = await ctx.ui.select('Which Prefactor agent should pi report to?', agents.length > 0 ? [CREATE_AGENT, USE_EXISTING_AGENT] : [CREATE_AGENT]);
206
+ if (choice === CREATE_AGENT) {
207
+ return createNamedAgent(ctx, api, agents);
208
+ }
209
+ if (choice === USE_EXISTING_AGENT) {
210
+ return chooseExistingAgent(ctx, agents);
211
+ }
212
+ return undefined;
213
+ }
214
+ async function createNamedAgent(ctx, api, agents) {
215
+ // pi's terminal UI does not show input placeholders, so the titles also name the defaults.
216
+ const name = await ctx.ui.input(`Name for the new agent (default: ${DEFAULT_AGENT_NAME})`, DEFAULT_AGENT_NAME);
217
+ if (name === undefined) {
218
+ return undefined;
219
+ }
220
+ const agentName = name.trim() || DEFAULT_AGENT_NAME;
221
+ const existing = agents.find((agent) => agent.name === agentName);
222
+ if (existing) {
223
+ const useExisting = await ctx.ui.confirm(`An agent named "${agentName}" already exists`, 'Use the existing agent instead?');
224
+ return useExisting ? existing : undefined;
225
+ }
226
+ const description = await ctx.ui.input(`Description (optional, default: ${DEFAULT_AGENT_DESCRIPTION})`, DEFAULT_AGENT_DESCRIPTION);
227
+ if (description === undefined) {
228
+ return undefined;
229
+ }
230
+ return api.createAgent(agentName, description.trim() || DEFAULT_AGENT_DESCRIPTION);
231
+ }
232
+ /**
233
+ * Lets the user pick one of the account's agents: a type-to-filter list in pi's terminal UI, or a
234
+ * plain list where custom UI is not available, such as RPC mode.
235
+ */
236
+ async function chooseExistingAgent(ctx, agents) {
237
+ const labels = agents.map((agent) => agents.filter((other) => other.name === agent.name).length > 1
238
+ ? `${agent.name} (${agent.id})`
239
+ : agent.name);
240
+ const title = 'Choose the agent pi reports to';
241
+ const choice = ctx.mode === 'tui'
242
+ ? await ctx.ui.custom((tui, theme, keybindings, done) => {
243
+ const filter = new Input({ placeholder: 'Type to filter' });
244
+ filter.focused = true;
245
+ const list = new SelectList(labels.map((label) => ({ value: label, label })), Math.min(labels.length, 10), {
246
+ selectedPrefix: (text) => theme.fg('accent', text),
247
+ selectedText: (text) => theme.fg('accent', text),
248
+ description: (text) => theme.fg('muted', text),
249
+ scrollInfo: (text) => theme.fg('dim', text),
250
+ // SelectList's own empty-filter text speaks of commands.
251
+ noMatch: () => theme.fg('warning', ' No matching agents'),
252
+ });
253
+ list.onSelect = (item) => done(item.value);
254
+ list.onCancel = () => done(undefined);
255
+ const container = new Container();
256
+ container.addChild(new Text(theme.fg('accent', title)));
257
+ container.addChild(filter);
258
+ container.addChild(list);
259
+ container.addChild(new Text(theme.fg('dim', 'type to filter · ↑↓ navigate · enter select · esc cancel')));
260
+ const listKeys = [
261
+ 'tui.select.up',
262
+ 'tui.select.down',
263
+ 'tui.select.pageUp',
264
+ 'tui.select.pageDown',
265
+ 'tui.select.confirm',
266
+ 'tui.select.cancel',
267
+ ];
268
+ return {
269
+ render: (width) => container.render(width),
270
+ invalidate: () => container.invalidate(),
271
+ handleInput(data) {
272
+ if (listKeys.some((key) => keybindings.matches(data, key))) {
273
+ list.handleInput(data);
274
+ }
275
+ else {
276
+ filter.handleInput(data);
277
+ list.setFilter(filter.getValue());
278
+ }
279
+ tui.requestRender();
280
+ },
281
+ };
282
+ })
283
+ : await ctx.ui.select(title, labels);
284
+ return choice === undefined ? undefined : agents[labels.indexOf(choice)];
285
+ }
286
+ /**
287
+ * Chooses the environment as `prefactor setup` does: the environment of the agent's only
288
+ * deployment, or of its only deployment with a current version. Otherwise the user chooses.
289
+ */
290
+ async function chooseEnvironment(ctx, api, agentId, accountId) {
291
+ const deployments = await api.listDeployments(agentId);
292
+ if (deployments.length === 1) {
293
+ return deployments[0].environment_id;
294
+ }
295
+ const current = deployments.filter((deployment) => deployment.current_version_id !== null);
296
+ if (current.length === 1) {
297
+ return current[0].environment_id;
298
+ }
299
+ const environments = await api.listEnvironments(accountId);
300
+ const candidates = deployments.length > 0
301
+ ? environments.filter((environment) => deployments.some((deployment) => deployment.environment_id === environment.id))
302
+ : environments;
303
+ if (candidates.length === 0) {
304
+ throw new Error('The account has no environments. Create one in Prefactor first.');
305
+ }
306
+ if (candidates.length === 1) {
307
+ return candidates[0].id;
308
+ }
309
+ const labels = candidates.map((environment) => `${environment.name} (${environment.id})`);
310
+ const choice = await ctx.ui.select('Which environment should pi report to?', labels);
311
+ return choice === undefined ? undefined : candidates[labels.indexOf(choice)].id;
312
+ }
313
+ async function checkDeploymentToken(host, apiUrl, token, agentId) {
314
+ const details = await new PrefactorApi(host.createClient(apiUrl, token)).ping();
315
+ if (details.token_type !== DEPLOYMENT_TOKEN_TYPE || details.agent_id !== agentId) {
316
+ throw new Error('The new deployment token did not pass its check.');
317
+ }
318
+ }
319
+ /**
320
+ * Revokes the account token from the sign-in with the token itself, so it is never left valid.
321
+ */
322
+ async function revokeAccountToken(ctx, api) {
323
+ try {
324
+ const { api_token_id: tokenId } = await api.ping();
325
+ if (!tokenId) {
326
+ throw new Error('ping returned no api_token_id');
327
+ }
328
+ await api.revokeToken(tokenId);
329
+ }
330
+ catch (error) {
331
+ ctx.ui.notify(`Could not revoke the sign-in token (${describe(error)}). Revoke it under Account settings in Prefactor.`, 'warning');
332
+ }
333
+ }
334
+ async function setupWithPastedToken(ctx, host, apiUrl) {
335
+ ctx.ui.notify('The token you paste is visible on screen.', 'warning');
336
+ const token = (await ctx.ui.input('Paste an agent-deployment token'))?.trim();
337
+ if (!token) {
338
+ return false;
339
+ }
340
+ const details = await new PrefactorApi(host.createClient(apiUrl, token)).ping();
341
+ if (details.token_type !== DEPLOYMENT_TOKEN_TYPE || !details.agent_id) {
342
+ throw new Error('That is not an agent-deployment token.');
343
+ }
344
+ await writeCredentialsFile({
345
+ api_url: apiUrl,
346
+ api_token: token,
347
+ agent_id: details.agent_id,
348
+ ...(details.environment_id ? { environment_id: details.environment_id } : {}),
349
+ // A deployment token cannot read its agent's or account's name, so only ids are saved.
350
+ ...(details.account_id ? { account_id: details.account_id } : {}),
351
+ created_at: new Date().toISOString(),
352
+ });
353
+ ctx.ui.notify(`Connected pi to the Prefactor agent ${details.agent_id}.`, 'info');
354
+ return true;
355
+ }
356
+ async function status(ctx, host) {
357
+ const recording = host.getRecording();
358
+ const credentials = await host.resolveCredentials();
359
+ const file = credentials?.source === 'file' ? await readCredentialsFile() : undefined;
360
+ const lines = recording
361
+ ? [
362
+ `This session records to ${recording.credentials.apiUrl}, agent ${recording.credentials.agentId ?? '(read from the token)'}, with credentials from the ${SOURCE_LABELS[recording.credentials.source]}.`,
363
+ recording.lastError
364
+ ? `Last request to Prefactor failed: ${describe(recording.lastError)}`
365
+ : 'Last request to Prefactor succeeded.',
366
+ ]
367
+ : ['This session is not being recorded.'];
368
+ if (credentials) {
369
+ lines.push(`New sessions use credentials from the ${SOURCE_LABELS[credentials.source]}${credentials.source === 'file' ? ` (${getCredentialsFilePath()})` : ''}:`, ` API URL: ${credentials.apiUrl}`, ...(file?.account_name || file?.account_id
370
+ ? [` Account: ${file.account_name ?? file.account_id}`]
371
+ : []), ` Agent: ${file?.agent_name ?? credentials.agentId ?? '(read from the token)'}`);
372
+ }
373
+ else {
374
+ lines.push('Prefactor is not set up. Run /prefactor setup to connect pi to Prefactor.');
375
+ }
376
+ ctx.ui.notify(lines.join('\n'), 'info');
377
+ }
378
+ async function logout(ctx, host) {
379
+ const deleted = await deleteCredentialsFile();
380
+ const remaining = await host.resolveCredentials();
381
+ const message = [
382
+ deleted
383
+ ? `Deleted ${getCredentialsFilePath()}.`
384
+ : `There is no credentials file at ${getCredentialsFilePath()}.`,
385
+ ...(remaining
386
+ ? [`Credentials from the ${SOURCE_LABELS[remaining.source]} are unaffected.`]
387
+ : []),
388
+ ...(host.getRecording() ? ['This session keeps recording until it ends.'] : []),
389
+ ];
390
+ ctx.ui.notify(message.join(' '), 'info');
391
+ }
392
+ function describe(error) {
393
+ return error instanceof Error ? error.message : String(error);
394
+ }
395
+ //# sourceMappingURL=commands.js.map