@oyasmi/pipiclaw 0.8.10 → 0.8.11-beta.3

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 (106) hide show
  1. package/README.md +3 -3
  2. package/dist/agent/channel-runner.d.ts +11 -0
  3. package/dist/agent/channel-runner.js +58 -27
  4. package/dist/agent/commands.js +2 -3
  5. package/dist/agent/effect-ledger.d.ts +1 -1
  6. package/dist/agent/effect-ledger.js +2 -2
  7. package/dist/agent/prompt/sections.js +3 -3
  8. package/dist/agent/runner-factory.d.ts +2 -0
  9. package/dist/agent/session-events.js +1 -1
  10. package/dist/main.js +6 -0
  11. package/dist/memory/commands.js +6 -1
  12. package/dist/memory/consolidation.d.ts +8 -1
  13. package/dist/memory/consolidation.js +34 -6
  14. package/dist/memory/extraction.d.ts +11 -3
  15. package/dist/memory/extraction.js +19 -6
  16. package/dist/memory/files.d.ts +2 -0
  17. package/dist/memory/files.js +14 -0
  18. package/dist/memory/maintenance-gates.d.ts +3 -0
  19. package/dist/memory/maintenance-gates.js +5 -2
  20. package/dist/memory/maintenance-jobs.js +19 -2
  21. package/dist/memory/maintenance-state.d.ts +29 -0
  22. package/dist/memory/maintenance-state.js +100 -8
  23. package/dist/memory/metadata.d.ts +9 -0
  24. package/dist/memory/metadata.js +5 -0
  25. package/dist/memory/probation.d.ts +21 -0
  26. package/dist/memory/probation.js +48 -0
  27. package/dist/memory/promotion.d.ts +26 -1
  28. package/dist/memory/promotion.js +34 -4
  29. package/dist/memory/recall.js +38 -19
  30. package/dist/memory/session-corpus.js +12 -11
  31. package/dist/memory/session-search.js +25 -6
  32. package/dist/memory/sidecar-worker.js +2 -0
  33. package/dist/memory/task-digest.d.ts +3 -2
  34. package/dist/memory/task-digest.js +22 -8
  35. package/dist/models/auth-cli.d.ts +25 -0
  36. package/dist/models/auth-cli.js +344 -0
  37. package/dist/models/login-ui.d.ts +35 -0
  38. package/dist/models/login-ui.js +145 -0
  39. package/dist/models/provider-login.d.ts +41 -0
  40. package/dist/models/provider-login.js +126 -0
  41. package/dist/models/utils.d.ts +6 -0
  42. package/dist/models/utils.js +10 -0
  43. package/dist/playbooks/memory-and-learning.md +7 -1
  44. package/dist/playbooks/outbound-media.md +7 -33
  45. package/dist/playbooks/runtime-orientation.md +2 -0
  46. package/dist/playbooks/task-closeout.md +22 -35
  47. package/dist/playbooks/task-delegation.md +13 -35
  48. package/dist/playbooks/task-driving.md +36 -56
  49. package/dist/playbooks/task-planning.md +26 -45
  50. package/dist/runtime/bootstrap.js +48 -14
  51. package/dist/runtime/delivery.js +8 -2
  52. package/dist/runtime/dingtalk.d.ts +6 -3
  53. package/dist/runtime/dingtalk.js +6 -39
  54. package/dist/runtime/events.js +4 -3
  55. package/dist/runtime/proxy.d.ts +36 -0
  56. package/dist/runtime/proxy.js +68 -0
  57. package/dist/runtime/store.d.ts +8 -2
  58. package/dist/runtime/store.js +12 -6
  59. package/dist/runtime/task-commands.d.ts +0 -2
  60. package/dist/runtime/task-commands.js +99 -112
  61. package/dist/runtime/task-driver.d.ts +5 -0
  62. package/dist/runtime/task-driver.js +155 -53
  63. package/dist/runtime/task-migration.d.ts +9 -0
  64. package/dist/runtime/task-migration.js +75 -2
  65. package/dist/security/command-guard.js +51 -17
  66. package/dist/security/path-guard.js +72 -14
  67. package/dist/shared/open-browser.d.ts +6 -0
  68. package/dist/shared/open-browser.js +22 -0
  69. package/dist/shared/recoverable-error.d.ts +1 -1
  70. package/dist/shared/recoverable-error.js +1 -1
  71. package/dist/subagents/tool.js +2 -0
  72. package/dist/tasks/control.d.ts +38 -67
  73. package/dist/tasks/control.js +90 -152
  74. package/dist/tasks/ledger.d.ts +104 -22
  75. package/dist/tasks/ledger.js +419 -56
  76. package/dist/tasks/store.d.ts +11 -10
  77. package/dist/tasks/store.js +58 -27
  78. package/dist/tasks/transitions.d.ts +8 -36
  79. package/dist/tasks/transitions.js +29 -54
  80. package/dist/tasks/verification.d.ts +2 -2
  81. package/dist/tools/index.d.ts +2 -0
  82. package/dist/tools/index.js +1 -0
  83. package/dist/tools/memory-manage.js +8 -1
  84. package/dist/tools/read.js +19 -5
  85. package/dist/tools/registry.d.ts +1 -0
  86. package/dist/tools/registry.js +1 -0
  87. package/dist/tools/task-manage/lifecycle.d.ts +1 -7
  88. package/dist/tools/task-manage/lifecycle.js +76 -77
  89. package/dist/tools/task-manage/schema.d.ts +10 -5
  90. package/dist/tools/task-manage/schema.js +35 -21
  91. package/dist/tools/task-manage/shared.d.ts +1 -1
  92. package/dist/tools/task-manage/shared.js +29 -30
  93. package/dist/tools/task-manage/types.d.ts +7 -1
  94. package/dist/tools/task-manage/verification.d.ts +4 -5
  95. package/dist/tools/task-manage/verification.js +43 -15
  96. package/dist/tools/task-manage.d.ts +1 -1
  97. package/dist/tools/task-manage.js +9 -9
  98. package/dist/tui/app.js +1 -2
  99. package/dist/tui/commands.d.ts +1 -1
  100. package/dist/tui/commands.js +1 -1
  101. package/dist/tui/turn-controller.d.ts +1 -1
  102. package/dist/usage/ledger.d.ts +1 -1
  103. package/dist/usage/ledger.js +47 -22
  104. package/dist/usage/render.d.ts +1 -1
  105. package/dist/usage/render.js +8 -6
  106. package/package.json +7 -6
@@ -42,11 +42,26 @@ function computeRecencyBoost(timestamp) {
42
42
  }
43
43
  return 0;
44
44
  }
45
- function scoreDocument(document, query, queryTokens) {
46
- const text = document.text;
47
- const lowerText = text.toLowerCase();
48
- const lowerQuery = query.trim().toLowerCase();
49
- const documentTokens = new Set(tokenizeRecallText(text));
45
+ /**
46
+ * Tokenizing a document is by far the most expensive part of a search — a few milliseconds for a
47
+ * multi-kilobyte transcript hit, times every document in the corpus. The corpus itself is already
48
+ * cached for {@link CORPUS_CACHE_TTL_MS}, so keying off the document's object identity keeps every
49
+ * search inside that window from re-deriving tokens it has already derived. Entries disappear with
50
+ * the cached corpus that owns them.
51
+ */
52
+ const documentTokenCache = new WeakMap();
53
+ function getDocumentTokens(document) {
54
+ const cached = documentTokenCache.get(document);
55
+ if (cached) {
56
+ return cached;
57
+ }
58
+ const tokens = new Set(tokenizeRecallText(document.text));
59
+ documentTokenCache.set(document, tokens);
60
+ return tokens;
61
+ }
62
+ function scoreDocument(document, lowerQuery, queryTokens) {
63
+ const lowerText = document.text.toLowerCase();
64
+ const documentTokens = getDocumentTokens(document);
50
65
  const matches = [];
51
66
  let matchedTokens = 0;
52
67
  for (const token of queryTokens) {
@@ -143,9 +158,13 @@ export async function searchChannelSessions(request) {
143
158
  .filter((document) => roleFilter.size === 0 || roleFilter.has(document.role))
144
159
  .sort(sortRecentDocuments)
145
160
  .slice(0, maxChunks);
161
+ // Both derived once, not per document: `tokenizeRecallText` is milliseconds on real input and
162
+ // this loop runs over the whole corpus.
163
+ const queryTokens = query ? tokenizeRecallText(query) : [];
164
+ const lowerQuery = query.toLowerCase();
146
165
  const selected = query
147
166
  ? documents
148
- .map((document) => scoreDocument(document, query, tokenizeRecallText(query)))
167
+ .map((document) => scoreDocument(document, lowerQuery, queryTokens))
149
168
  .filter((entry) => entry.score > 0)
150
169
  .sort((a, b) => b.score - a.score)
151
170
  .slice(0, limit)
@@ -1,4 +1,5 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
2
3
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
3
4
  import { formatModelReference } from "../models/utils.js";
4
5
  import { extractAssistantText } from "../shared/text-utils.js";
@@ -94,6 +95,7 @@ export async function runSidecarTask(task) {
94
95
  },
95
96
  convertToLlm,
96
97
  getApiKey: async () => apiKey,
98
+ streamFn: streamSimple,
97
99
  });
98
100
  const abortWorker = () => {
99
101
  try {
@@ -19,7 +19,8 @@ export interface TaskDigestOptions {
19
19
  now?: number;
20
20
  }
21
21
  /**
22
- * Render the in-flight task agenda, or `""` when there is nothing actionable to show.
23
- * Only status ≠ done tasks are included (a done periodic task is sleeping, not on the agenda).
22
+ * Render the in-flight task agenda, or `""` when there are no live tasks to show.
23
+ * Sleeping and disabled tasks stay visible so the model can distinguish dormant work from lost
24
+ * work and tell the user which recovery source is needed.
24
25
  */
25
26
  export declare function buildTaskDigest(options: TaskDigestOptions): Promise<string>;
@@ -19,21 +19,33 @@ function relativeWake(wakeMs, now) {
19
19
  }
20
20
  function renderLine(entry, now) {
21
21
  const status = entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "⚠ unreadable frontmatter";
22
- const parts = [`${entry.id} — ${entry.title}`, status, relativeWake(entry.wakeMs, now)];
22
+ const parts = [
23
+ `${entry.id} — ${entry.title}`,
24
+ status,
25
+ entry.frontmatter.enabled === false ? "disabled" : "enabled",
26
+ relativeWake(entry.wakeMs, now),
27
+ ];
23
28
  const control = entry.frontmatter.control;
24
29
  if (control) {
25
30
  parts.push(`priority ${control.priority}`);
26
31
  parts.push(`attempt ${control.usage.attempts}/${control.budget.maxAttempts}`);
27
32
  if (control.verification.required)
28
33
  parts.push(`verify required/${control.verification.status}`);
29
- if (control.sideEffects !== "workspace") {
30
- parts.push(`effects ${control.sideEffects}/${control.externalApproval}`);
31
- }
34
+ if (control.waitingFor)
35
+ parts.push(`waiting for ${control.waitingFor}`);
36
+ if (control.stop)
37
+ parts.push(`stop ${control.stop.by}: ${control.stop.reason}`);
32
38
  if (control.deadline)
33
39
  parts.push(`deadline ${control.deadline}`);
34
40
  if (control.nextAction)
35
41
  parts.push(`next ${control.nextAction}`);
36
42
  }
43
+ // spec 037, D4: the agenda shows Plan progress and the current step, not the full Plan — the
44
+ // complete section is only read from the task file at wake time (task-driver.ts's capsule),
45
+ // staying well inside the 600-unit budget this block competes for (spec 025/026).
46
+ if (entry.plan) {
47
+ parts.push(`plan ${entry.plan.done}/${entry.plan.total} · @${entry.plan.current?.id ?? "-"}`);
48
+ }
37
49
  if (entry.latestNote) {
38
50
  const note = entry.latestNote.length > 80 ? `${entry.latestNote.slice(0, 79)}…` : entry.latestNote;
39
51
  parts.push(note);
@@ -41,15 +53,17 @@ function renderLine(entry, now) {
41
53
  return `- ${parts.join(" · ")}`;
42
54
  }
43
55
  /**
44
- * Render the in-flight task agenda, or `""` when there is nothing actionable to show.
45
- * Only status ≠ done tasks are included (a done periodic task is sleeping, not on the agenda).
56
+ * Render the in-flight task agenda, or `""` when there are no live tasks to show.
57
+ * Sleeping and disabled tasks stay visible so the model can distinguish dormant work from lost
58
+ * work and tell the user which recovery source is needed.
46
59
  */
47
60
  export async function buildTaskDigest(options) {
48
61
  const now = options.now ?? Date.now();
49
62
  const tasksDir = join(options.channelDir, "tasks");
50
63
  const all = await readActiveTasks(tasksDir, now);
51
- // done periodic tasks are asleep; only non-done tasks form the agenda.
52
- const agenda = all.filter((entry) => entry.frontmatter.status !== "done" || !entry.frontmatter.readable);
64
+ // A legacy terminal file may briefly remain in the active directory while startup migration
65
+ // is running. It is already non-actionable at the ledger layer and must not enter prompt context.
66
+ const agenda = all.filter((entry) => !entry.frontmatter.archiveOutcome);
53
67
  if (agenda.length === 0)
54
68
  return "";
55
69
  const shown = agenda.slice(0, Math.max(1, options.maxTasks));
@@ -0,0 +1,25 @@
1
+ import { type BootstrapIO, type BootstrapPaths } from "../runtime/bootstrap.js";
2
+ export type ParsedAuth = {
3
+ kind: "status";
4
+ } | {
5
+ kind: "login";
6
+ provider?: string;
7
+ apiKey: boolean;
8
+ oauth: boolean;
9
+ deviceCode: boolean;
10
+ noBrowser: boolean;
11
+ } | {
12
+ kind: "logout";
13
+ provider?: string;
14
+ yes: boolean;
15
+ } | {
16
+ kind: "help";
17
+ } | {
18
+ kind: "version";
19
+ } | {
20
+ kind: "error";
21
+ message: string;
22
+ };
23
+ /** Parse `pipiclaw auth` arguments (everything after the `auth` subcommand, including the subcommand name itself). */
24
+ export declare function parseAuthArgs(args: string[]): ParsedAuth;
25
+ export declare function runAuth(argv: string[], io?: BootstrapIO, paths?: BootstrapPaths): Promise<void>;
@@ -0,0 +1,344 @@
1
+ /**
2
+ * `pipiclaw auth` CLI: argument parsing and entry. Parsing is a pure function
3
+ * (`parseAuthArgs`) so it can be unit-tested; `runAuth` wires it to the
4
+ * transport-neutral orchestration in `provider-login.ts`. Deliberately does
5
+ * not construct a runner, session, memory scheduler, or channel directory —
6
+ * login is a short, one-shot operation (spec 039 §5.1).
7
+ */
8
+ import { createInterface } from "node:readline/promises";
9
+ import * as log from "../log.js";
10
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, prepareAppServices, printBootstrapSummary, readCliVersion, } from "../runtime/bootstrap.js";
11
+ import { ReadlineLoginUi } from "./login-ui.js";
12
+ import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
13
+ import { createModelRuntime, formatModelReference } from "./utils.js";
14
+ /** Parse `pipiclaw auth` arguments (everything after the `auth` subcommand, including the subcommand name itself). */
15
+ export function parseAuthArgs(args) {
16
+ if (args.length === 0) {
17
+ return { kind: "error", message: "Missing subcommand. Usage: pipiclaw auth status|login|logout" };
18
+ }
19
+ if (args[0] === "--version")
20
+ return { kind: "version" };
21
+ if (args[0] === "--help" || args[0] === "-h")
22
+ return { kind: "help" };
23
+ const subcommand = args[0];
24
+ const rest = args.slice(1);
25
+ if (subcommand === "status") {
26
+ if (rest.some((arg) => arg === "--help" || arg === "-h"))
27
+ return { kind: "help" };
28
+ if (rest.length > 0)
29
+ return { kind: "error", message: `Unknown option: ${rest[0]}` };
30
+ return { kind: "status" };
31
+ }
32
+ if (subcommand === "login") {
33
+ let apiKey = false;
34
+ let oauth = false;
35
+ let deviceCode = false;
36
+ let noBrowser = false;
37
+ const positional = [];
38
+ for (const arg of rest) {
39
+ if (arg === "--api-key")
40
+ apiKey = true;
41
+ else if (arg === "--oauth")
42
+ oauth = true;
43
+ else if (arg === "--device-code")
44
+ deviceCode = true;
45
+ else if (arg === "--no-browser")
46
+ noBrowser = true;
47
+ else if (arg === "--help" || arg === "-h")
48
+ return { kind: "help" };
49
+ else if (arg.startsWith("--"))
50
+ return { kind: "error", message: `Unknown option: ${arg}` };
51
+ else
52
+ positional.push(arg);
53
+ }
54
+ if (apiKey && oauth)
55
+ return { kind: "error", message: "--api-key and --oauth are mutually exclusive" };
56
+ if (positional.length > 1)
57
+ return { kind: "error", message: `Unexpected argument: ${positional[1]}` };
58
+ return { kind: "login", provider: positional[0], apiKey, oauth, deviceCode, noBrowser };
59
+ }
60
+ if (subcommand === "logout") {
61
+ let yes = false;
62
+ const positional = [];
63
+ for (const arg of rest) {
64
+ if (arg === "--yes" || arg === "-y")
65
+ yes = true;
66
+ else if (arg === "--help" || arg === "-h")
67
+ return { kind: "help" };
68
+ else if (arg.startsWith("--"))
69
+ return { kind: "error", message: `Unknown option: ${arg}` };
70
+ else
71
+ positional.push(arg);
72
+ }
73
+ if (positional.length > 1)
74
+ return { kind: "error", message: `Unexpected argument: ${positional[1]}` };
75
+ return { kind: "logout", provider: positional[0], yes };
76
+ }
77
+ return { kind: "error", message: `Unknown subcommand: ${subcommand}` };
78
+ }
79
+ function printAuthHelp(io) {
80
+ io.log("Usage: pipiclaw auth status|login|logout [options]");
81
+ io.log("");
82
+ io.log("Manage provider credentials stored in auth.json. A one-shot, interactive");
83
+ io.log("operation — it does not start the daemon, load memory, or touch any channel.");
84
+ io.log("");
85
+ io.log(" pipiclaw auth status");
86
+ io.log(" List configured providers, credential type, and the auth.json path.");
87
+ io.log("");
88
+ io.log(" pipiclaw auth login [provider] [--api-key] [--oauth] [--device-code] [--no-browser]");
89
+ io.log(" Log in to a provider. With no arguments, prompts for auth type then");
90
+ io.log(" provider. `provider` matches by id or name, case-insensitively.");
91
+ io.log(" --api-key / --oauth Skip the auth-type prompt.");
92
+ io.log(" --device-code Preset answer for headless OAuth flows (no local browser/port).");
93
+ io.log(" --no-browser Print the auth URL only; never try to open a browser.");
94
+ io.log("");
95
+ io.log(" pipiclaw auth logout [provider] [--yes]");
96
+ io.log(" Remove a stored credential. Confirms unless --yes is given.");
97
+ io.log("");
98
+ io.log("Note: a running daemon or TUI session must be restarted to see new credentials.");
99
+ }
100
+ function providerAuthAvailable(runtime, option) {
101
+ const provider = runtime.getProvider(option.id);
102
+ if (!provider)
103
+ return false;
104
+ return option.authType === "oauth"
105
+ ? provider.auth.oauth?.login !== undefined
106
+ : provider.auth.apiKey?.login !== undefined;
107
+ }
108
+ function toTarget(runtime, option) {
109
+ return providerAuthAvailable(runtime, option)
110
+ ? { kind: "target", providerId: option.id, authType: option.authType }
111
+ : { kind: "unsupported", name: option.name };
112
+ }
113
+ async function askAuthTypeChoice(ui) {
114
+ const answer = await ui.ask({
115
+ type: "select",
116
+ message: "Authentication method:",
117
+ options: [
118
+ { id: "oauth", label: "Subscription login (OAuth)" },
119
+ { id: "api_key", label: "API key" },
120
+ ],
121
+ });
122
+ return answer === "api_key" ? "api_key" : "oauth";
123
+ }
124
+ async function resolveLoginTarget(runtime, parsed, ui) {
125
+ const forcedAuthType = parsed.oauth ? "oauth" : parsed.apiKey ? "api_key" : undefined;
126
+ if (parsed.provider) {
127
+ const needle = parsed.provider.toLowerCase();
128
+ let candidates = listProviderLoginOptions(runtime).filter((option) => option.id.toLowerCase() === needle || option.name.toLowerCase() === needle);
129
+ if (forcedAuthType)
130
+ candidates = candidates.filter((option) => option.authType === forcedAuthType);
131
+ if (candidates.length === 0) {
132
+ throw new Error(`Unknown provider: "${parsed.provider}". Run \`pipiclaw auth status\` to see available providers.`);
133
+ }
134
+ let chosen = candidates[0];
135
+ if (candidates.length > 1) {
136
+ const authTypeId = await ui.ask({
137
+ type: "select",
138
+ message: `Select login method for ${chosen.name}:`,
139
+ options: candidates.map((candidate) => ({
140
+ id: candidate.authType,
141
+ label: candidate.authType === "oauth" ? (candidate.loginLabel ?? "OAuth") : "API key",
142
+ })),
143
+ });
144
+ chosen = candidates.find((candidate) => candidate.authType === authTypeId) ?? chosen;
145
+ }
146
+ return toTarget(runtime, chosen);
147
+ }
148
+ const authType = forcedAuthType ?? (await askAuthTypeChoice(ui));
149
+ const options = listProviderLoginOptions(runtime, authType);
150
+ if (options.length === 0) {
151
+ throw new Error(`No providers support ${authType === "oauth" ? "subscription login" : "API key login"}.`);
152
+ }
153
+ const providerId = await ui.ask({
154
+ type: "select",
155
+ message: "Select a provider:",
156
+ options: options.map((option) => ({
157
+ id: option.id,
158
+ label: option.name,
159
+ description: option.configured ? `configured (${option.configuredAs})` : "not configured",
160
+ })),
161
+ });
162
+ const chosen = options.find((option) => option.id === providerId);
163
+ if (!chosen)
164
+ throw new Error(`Unknown provider: "${providerId}".`);
165
+ return toTarget(runtime, chosen);
166
+ }
167
+ function auditAuthEvent(action, providerId, authType, ok) {
168
+ // Deliberately not routed through src/security/logger.ts: that module is
169
+ // scoped to per-channel blocked-operation audit (workspaceDir + SecurityConfig
170
+ // gate) and this is a process-level, channel-less event. Never includes a
171
+ // token/secret fragment.
172
+ log.logInfo(`auth ${action}: ${providerId}${authType ? ` (${authType})` : ""} — ${ok ? "ok" : "failed"}`);
173
+ }
174
+ async function runLogin(runtime, parsed, io, signal) {
175
+ const ui = new ReadlineLoginUi({
176
+ signal,
177
+ presetFirstSelect: parsed.deviceCode ? "device_code" : undefined,
178
+ noBrowser: parsed.noBrowser,
179
+ });
180
+ try {
181
+ const target = await resolveLoginTarget(runtime, parsed, ui);
182
+ if (target.kind === "unsupported") {
183
+ io.error(`"${target.name}" uses ambient credentials (environment variables / local config files), not interactive login.`);
184
+ io.error("See docs/configuration.md for how to configure it.");
185
+ throw new BootstrapExitError(1);
186
+ }
187
+ let result;
188
+ try {
189
+ result = await loginProvider(runtime, target.providerId, target.authType, ui);
190
+ }
191
+ catch (error) {
192
+ auditAuthEvent("login", target.providerId, target.authType, false);
193
+ throw error;
194
+ }
195
+ auditAuthEvent("login", target.providerId, target.authType, true);
196
+ io.log(`Logged in: ${target.providerId} (${result.credentialType})`);
197
+ if (result.newModels.length > 0) {
198
+ const sorted = result.newModels
199
+ .slice()
200
+ .sort((a, b) => formatModelReference(a).localeCompare(formatModelReference(b)));
201
+ io.log("New models available:");
202
+ for (const model of sorted)
203
+ io.log(` - ${formatModelReference(model)}`);
204
+ io.log("");
205
+ io.log("This does not change your default model. To use one of these:");
206
+ io.log(` /model ${formatModelReference(sorted[0])} (inside \`pipiclaw tui\`)`);
207
+ io.log("or add to settings.json:");
208
+ io.log(` { "defaultProvider": "${sorted[0].provider}", "defaultModel": "${sorted[0].id}" }`);
209
+ }
210
+ io.log("A running daemon or TUI session must be restarted to see this credential.");
211
+ if (process.env.PIPICLAW_PROXY && !process.env.HTTPS_PROXY && !process.env.HTTP_PROXY) {
212
+ io.log("");
213
+ io.log("Warning: PIPICLAW_PROXY is set but HTTPS_PROXY/HTTP_PROXY is not. Codex chat traffic uses a " +
214
+ "WebSocket transport that only honors HTTPS_PROXY/HTTP_PROXY and may connect directly — see " +
215
+ "docs/configuration.md.");
216
+ }
217
+ }
218
+ catch (error) {
219
+ if (error instanceof BootstrapExitError)
220
+ throw error;
221
+ if (error instanceof LoginCancelledError || signal.aborted) {
222
+ io.error("Cancelled.");
223
+ throw new BootstrapExitError(130);
224
+ }
225
+ io.error(error instanceof Error ? error.message : String(error));
226
+ throw new BootstrapExitError(2);
227
+ }
228
+ finally {
229
+ ui.close();
230
+ }
231
+ }
232
+ async function runLogout(runtime, parsed, io, signal) {
233
+ const credentials = await runtime.listCredentials();
234
+ if (credentials.length === 0) {
235
+ io.log("No stored credentials.");
236
+ return;
237
+ }
238
+ const providerNames = new Map(runtime.getProviders().map((provider) => [provider.id, provider.name]));
239
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
240
+ try {
241
+ let providerId = parsed.provider;
242
+ if (providerId) {
243
+ const needle = providerId.toLowerCase();
244
+ const match = credentials.find((credential) => credential.providerId.toLowerCase() === needle ||
245
+ (providerNames.get(credential.providerId) ?? "").toLowerCase() === needle);
246
+ if (!match) {
247
+ io.error(`No stored credential for "${providerId}". Run \`pipiclaw auth status\` to see what's configured.`);
248
+ throw new BootstrapExitError(1);
249
+ }
250
+ providerId = match.providerId;
251
+ }
252
+ else if (credentials.length === 1) {
253
+ providerId = credentials[0].providerId;
254
+ }
255
+ else {
256
+ io.error("Select a provider to log out:");
257
+ credentials.forEach((credential, index) => {
258
+ io.error(` ${index + 1}) ${providerNames.get(credential.providerId) ?? credential.providerId} (${credential.type})`);
259
+ });
260
+ const raw = (await rl.question("> ", { signal })).trim();
261
+ const index = Number.parseInt(raw, 10);
262
+ const match = Number.isInteger(index) ? credentials[index - 1] : undefined;
263
+ if (!match) {
264
+ io.error(`Invalid choice: ${raw}`);
265
+ throw new BootstrapExitError(1);
266
+ }
267
+ providerId = match.providerId;
268
+ }
269
+ const displayName = providerNames.get(providerId) ?? providerId;
270
+ if (!parsed.yes) {
271
+ const answer = (await rl.question(`Log out of ${displayName}? [y/N] `, { signal })).trim().toLowerCase();
272
+ if (answer !== "y" && answer !== "yes") {
273
+ io.log("Cancelled.");
274
+ return;
275
+ }
276
+ }
277
+ try {
278
+ await logoutProvider(runtime, providerId);
279
+ }
280
+ catch (error) {
281
+ auditAuthEvent("logout", providerId, undefined, false);
282
+ io.error(error instanceof Error ? error.message : String(error));
283
+ throw new BootstrapExitError(2);
284
+ }
285
+ auditAuthEvent("logout", providerId, undefined, true);
286
+ io.log(`Logged out: ${displayName}`);
287
+ }
288
+ catch (error) {
289
+ if (error instanceof BootstrapExitError)
290
+ throw error;
291
+ if (signal.aborted) {
292
+ io.error("Cancelled.");
293
+ throw new BootstrapExitError(130);
294
+ }
295
+ throw error;
296
+ }
297
+ finally {
298
+ rl.close();
299
+ }
300
+ }
301
+ export async function runAuth(argv, io = console, paths = DEFAULT_BOOTSTRAP_PATHS) {
302
+ const parsed = parseAuthArgs(argv.slice(3));
303
+ if (parsed.kind === "help") {
304
+ printAuthHelp(io);
305
+ return;
306
+ }
307
+ if (parsed.kind === "version") {
308
+ io.log(readCliVersion());
309
+ return;
310
+ }
311
+ if (parsed.kind === "error") {
312
+ io.error(parsed.message);
313
+ io.error("Run `pipiclaw auth --help` for usage.");
314
+ throw new BootstrapExitError(1);
315
+ }
316
+ if (parsed.kind !== "status" && process.stdin.isTTY !== true) {
317
+ io.error("pipiclaw auth login/logout requires an interactive terminal (stdin is not a TTY).");
318
+ throw new BootstrapExitError(1);
319
+ }
320
+ printBootstrapSummary(bootstrapAppHome(paths, io), io, paths);
321
+ prepareAppServices(paths);
322
+ const runtime = await createModelRuntime({
323
+ authConfigPath: paths.authConfigPath,
324
+ modelsConfigPath: paths.modelsConfigPath,
325
+ });
326
+ if (parsed.kind === "status") {
327
+ io.log(await renderAuthStatus(runtime, paths.authConfigPath));
328
+ return;
329
+ }
330
+ const controller = new AbortController();
331
+ const onSigint = () => controller.abort();
332
+ process.once("SIGINT", onSigint);
333
+ try {
334
+ if (parsed.kind === "login") {
335
+ await runLogin(runtime, parsed, io, controller.signal);
336
+ }
337
+ else {
338
+ await runLogout(runtime, parsed, io, controller.signal);
339
+ }
340
+ }
341
+ finally {
342
+ process.removeListener("SIGINT", onSigint);
343
+ }
344
+ }
@@ -0,0 +1,35 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import type { AuthEvent, AuthPrompt } from "@earendil-works/pi-ai";
3
+ import { type LoginUi } from "./provider-login.js";
4
+ export interface ReadlineLoginUiOptions {
5
+ input?: Readable;
6
+ output?: Writable;
7
+ signal?: AbortSignal;
8
+ /** Preset answer id for the first `select` prompt only (backs `--device-code`). */
9
+ presetFirstSelect?: string;
10
+ /** Skip opening a browser for `auth_url` events (backs `--no-browser`). */
11
+ noBrowser?: boolean;
12
+ }
13
+ export declare class ReadlineLoginUi implements LoginUi {
14
+ readonly signal: AbortSignal;
15
+ private readonly rl;
16
+ private readonly output;
17
+ private readonly presetFirstSelect?;
18
+ private readonly noBrowser;
19
+ private firstSelectConsumed;
20
+ constructor(options?: ReadlineLoginUiOptions);
21
+ ask(prompt: AuthPrompt): Promise<string>;
22
+ notify(event: AuthEvent): void;
23
+ /** Release stdin so the process can exit after the login flow finishes. */
24
+ close(): void;
25
+ private formatPrompt;
26
+ /**
27
+ * Shared question path. Combines the overall SIGINT signal (→
28
+ * `LoginCancelledError`) with a per-prompt signal (→ quiet empty-string
29
+ * resolution, used when `manual_code` loses its race against the OAuth
30
+ * callback server).
31
+ */
32
+ private question;
33
+ private askSecret;
34
+ private askSelect;
35
+ }