Commit Graph
358 Commits
Author SHA1 Message Date
ZacharyZhang-NY ecd1bc2e33 refactor(worker): single active-run map replaces parallel claim structures
Worker scheduling invariants ("one agent at a time", "one exclusive
workspace lock at a time") were enforced across three parallel
structures: `activeByAgent: Map<string, string>`,
`activeByWorkspace: Map<string, string>`, and `queue: RunJob[]`. Every
claim, release, and tick had to update them in lockstep, with defensive
comments explaining the ordering to future readers.

Replace with one `active: Map<runId, ActiveRun>` where ActiveRun
carries agentId + workspaceKey. Busy checks iterate the map (≤ dozens
of entries); dispatch is a single set + splice. Release is a single
delete. No parallel structures to keep in sync.

- Add `isAgentBusy(agentId)` and `isWorkspaceBusy(lockKey)` as local
  helpers — both O(n) over the active map, which is fine at this scale.
- `tickQueue` is claim-before-dispatch: writes `active.set` synchronously
  before `startRun` so no async window exists between claim and
  dispatch.
- Drop the `lockKey` parameter threading through `startRun` — the map
  carries it.
2026-04-17 15:07:27 -04:00
ZacharyZhang-NY 883fd8e118 fix(skills): honor agent_skill_assignments in runtime skill projection
After Wave D1 switched to pi-coding-agent's loadSkills, the runtime
ignored the per-agent assignment table entirely — every agent saw the
full company catalog. The UI (SkillAgentToggles) still let users curate
which skills each agent should see, so user decisions silently did
nothing.

Pi's progressive-disclosure model accepts a skillPaths list at load
time. Use that to pass only assigned skills, preserving the user's
curation while keeping the description-only prompt footprint.

- listRuntimeSkillEntries reads db.listAgentSkillAssignments(agentId),
  filters company skills to the assigned set, passes only those paths
  to loadSkills.
- Empty assignment set short-circuits (no SKILL.md scan, no prompt
  section).
- connectorId parameter stays for signature compatibility; no current
  connector-specific policy applies.

UI contract unchanged. Runtime now obeys it.
2026-04-17 15:05:20 -04:00
ZacharyZhang-NY 14dc9a4897 refactor(cost): single writer for cost_entries, finishRun reads SUM
Cost was written through three independent paths: worker-runner shipped
`finalUsage.costUsd` in run-finished -> finishRun wrote `runs.cost_usd`,
`tasks.cost_usd += costUsd`, `agents.spent_monthly_usd += costUsd`, and
inserted a per-run aggregate row in cost_entries. CostWriter
additionally inserted per-message rows in cost_entries from main. Any
CostWriter failure created silent drift between `SUM(cost_entries)`
(read by budget enforcement) and `runs.cost_usd` (read by the UI).

Make CostWriter the single writer, finishRun the single reader.

- Add `db.recordCostEntry(...)` as the first-class insert path for
  per-message cost rows. CostWriter calls it; tests call it directly.
- Remove the aggregate INSERT from finishRun. finishRun now reads
  `SELECT COALESCE(SUM(amount_usd), 0) FROM cost_entries WHERE run_id=?
  AND unattributed=0` and writes that as the authoritative run total to
  runs.cost_usd, tasks.cost_usd, and agents.spent_monthly_usd.
- Drop `costUsd` from `finishRun` input, the worker `run-finished`
  ChildMessage shape, the automation `RunFinishedEvent` type, and every
  caller + test fixture. Cost is owned by the per-message path.
- worker-runner stops extracting `usage.cost.total` — token counts stay
  for session accumulation, cost comes from pi-ai via CostWriter.
- run-finished-helpers now gates budget incident checks on
  `event.status === "succeeded"` instead of a cost field that no longer
  exists on the event.
- automation-run-completion fires `budget_threshold` on every succeeded
  run (post-run spent_monthly_usd already reflects the SUM path).
- Update budget tests to write a `recordCostEntry` before `finishRun`
  to simulate the per-message cost path; drop `costUsd` from cross-
  subsystem, edge-case-budget, database, and related fixtures.

One writer, one reader, one source of truth. No drift.
2026-04-17 15:04:22 -04:00
ZacharyZhang-NY 77f81a7c5a fix(runtime): revive AI Co-Founder tool-call gating via pi beforeToolCall
An earlier cleanup deleted HumanApprovalHook wholesale on the rationale
that the body always returned {}. That was the stub implementation, not
the feature: 版本更新.md specifies AI Co-Founder mode as "human-reviewed
execution that pauses until human review arrives". With no beforeToolCall
attached, Co-Founder and CEO modes behaved identically — a silent
regression of the product's core differentiator.

Bring the hook back with real gating logic and split the Agent
construction path by execution mode so CEO runs pay zero IPC overhead.

- HumanApprovalHook.before(): create a `dangerous_command` approval row
  for non-whitelisted tool calls, emit approval-updated, return a promise
  that resolves when a human decides.
- AUTO_APPROVED_TOOLS whitelist: read/ls/glob/grep/find/tree. Anything
  else (bash, write, edit, …) waits for human approval.
- approvalHook.resolveApproval(): invoked from wire-api-server's
  onApprovalResolved *before* automation and thread follow-ups, so the
  pi Agent unblocks the instant the human decides.
- approvalHook.cancelAll(): release every pending wait on shutdown so the
  worker can drain cleanly; wired into service-graph-pi-runtime.release.
- worker-runner: attach beforeToolCall only when job.executionMode ===
  "ai_cofounder". CEO mode constructs Agent with no hook, no RPC hops.
- WorkerRpcClient.invoke: accept per-call timeoutMs override so approval
  RPCs can wait 30min instead of the 30s default.
- worker-types schema: restore beforeToolCall in the method enum.
- RuntimeBridge.handleRpc: restore beforeToolCall branch.

No changes to approval DB schema, approval lifecycle, or existing
automation/thread handling. CEO-mode runs retain zero-IPC-per-tool
behavior from the prior cleanup.
2026-04-17 14:53:22 -04:00
ZacharyZhang-NY b50716d4e8 refactor(messaging): project inter-agent messages into pi session transcript
Inter-agent messages previously entered the recipient's context as a
separate prompt block (recentMessages), rebuilt every turn. This double-
charged tokens and kept messages outside pi's native AgentMessage stream.

Now at prepareRun: pull the recipient's unread inbox, project each
AgentMessageRecord into a pi user-role AgentMessage, persist to
SqliteSessionStore, and mark delivered. The recipient reads messages
as natural conversation turns in the transcript.

- db: listAgentInboxUnread + markAgentInboxDelivered (transactional)
- agent-runtime/inbox-projection.ts: AgentMessageRecord -> pi AgentMessage
- runtime-bridge.prepareRun: inject + deliver before loadMessages
- prompt-builder: delete recentMessages context block + buildMessagesSection
- message-normalize: drop unused normalizeMessagesForPrompt
- delete prompt-builder/attachment-resolver.ts (orphan after section removal)

Send path (api-server/routes-messages, ipc, UI) unchanged — inbox table
remains the UI source. Transactional delivery marking prevents duplicate
injection across runs. Failed append -> no mark -> retry on next run.
2026-04-17 14:48:22 -04:00
ZacharyZhang-NY 5547c29491 update 2026-04-17 14:03:56 -04:00
ZacharyZhang-NY 806200b3d1 fix(runtime): correct pi AgentEvent projection + add Console diagnostics
karpathy-guidelines pass — never guess at types, read the source.

Root cause of the silent "等待日志输出" Console:

1. runtime-bridge's projectAgentEventToLogChunk switched on event types
   that never exist in pi. Real types per pi-mono-reference/packages/
   agent/src/types.ts `AgentEvent`:
     agent_start / agent_end / turn_start / turn_end
     message_start / message_update / message_end
     tool_execution_start / tool_execution_update / tool_execution_end
   (NOT the `assistant_message_delta` / `tool_call_start` / `error` I
   invented.) Every case therefore fell through to `default → null`,
   so zero log chunks were emitted even when the agent was streaming
   tokens.

   Rewrote the switch to match the real union. Streaming assistant
   text and thinking now route through `message_update` ->
   `assistantMessageEvent.text_delta` / `thinking_delta` (see
   pi-mono-reference/packages/ai/src/types.ts `AssistantMessageEvent`
   for the inner protocol). Tool activity routes through
   `tool_execution_start` / `tool_execution_end`.

2. worker-runner had no Console-visible breadcrumbs between
   `run-status: running` and eventual turn output, so when the agent
   stalled (credential fetch, model resolution, first API call) the
   user saw a bare "RUNNING" with no clue where time was being spent.
   Added 5 targeted `run-log` probes:
     [runner] starting run ...
     [runner] prepareRun ok, resolving model
     [runner] model=... provider=... — constructing Agent
     [pi-event] <type>        (inside agent.subscribe, one per event)
     [runner] calling agent.prompt (N chars)
     [runner] agent.prompt resolved
   These are structured runtime signals, not test/mockup data. They
   surface the exact phase a stuck run is in.

typecheck 0 / lint 0-0 / test:unit 508/508 / build:verify 0-0.
2026-04-17 10:35:23 -04:00
ZacharyZhang-NY 7fc707ab8c fix(onboarding): stabilize connector-model state so native <select> stays open
The CEO-runtime model dropdown (and the team-model pool) collapsed the
instant a user clicked to open it whenever the app received a background
snapshot refresh. Root cause:

  useEffect(executionReadyConnectors, ...)
    → loadModels() loads catalog for every ready connector
    → setConnectorModelsById(Object.fromEntries(entries))
      — always a brand-new object reference, even if the catalog
        returned from the IPC is byte-identical to the previous load
    → connectorModels useMemo picks up a new reference
    → modelOptions useMemo picks up a new reference
    → <Select> re-renders its options children
    → Chromium's native <select> treats DOM mutation of <option>
      children as "popup stale" and closes the dropdown.

Because snapshot refreshes fire on every domain-changed event
(credentials-changed, run-status, heartbeat-status, etc.), the user
effectively could not hold the dropdown open long enough to pick a
model.

Fix: structurally compare the freshly-loaded catalog against the
previous state and bail out of setState when the shape is identical
(same connector ids, same per-connector model lists in order, same
id/label/enabled flags). Same guard on the error-path reset so an
already-empty map does not trigger a re-render either.

typecheck 0 / lint 0-0 / test:unit 508/508 / build 0-0.
2026-04-17 10:28:19 -04:00
ZacharyZhang-NY 683dded501 fix(runtime): autonomous beforeToolCall + project agent-event to Console log
Two coupled user-visible defects were fixed.

1. Every tool call (shell / edit / write / read / ...) triggered a
   synchronous human-approval prompt under BOTH execution modes. The
   worker blocked inside pi's beforeToolCall waiting on a DB approval
   row, so runs never progressed — "等待日志输出" forever.

   The execution-mode contract is now enforced:
   - AI CEO       → fully autonomous, no framework gate.
   - AI Co-Founder → still fully autonomous at the pi layer. Human
     review is a model-driven decision (LLM calls an explicit
     `request_approval` tool when it judges review necessary), not
     a framework-level interrupt.

   HumanApprovalHook collapses to a no-op `before` / `after` /
   `cancelAll`. All machinery that queued `dangerous_command`
   approvals from the worker-side hook is removed. No more starving
   the agent on `node -e` self-call checks.

2. The Console panel only subscribed to `run-log` stdout/stderr
   chunks, so pi's agent-event stream (assistant_message_delta,
   tool_call_start/end, errors, turn_end) produced zero visible
   output. With bug (1) fixed, runs now execute — but the user
   would still see a blank Console.

   runtime-bridge.handleAgentEvent now projects each meaningful
   agent-event into a run-log chunk (assistant_message_delta → raw
   delta, tool_call_start → `[tool:bash] {args}`, tool_call_end →
   `[tool:done|error:name] {result}`, error → stderr). ConsoleView
   picks these up via the existing run-log DesktopEvent pipe with
   no renderer change.

tests/unit/approval-hook.test.ts rewritten to assert the new
autonomous contract (before always returns {}, no approval rows
written, cancelAll is a no-op). Tests 508/508 pass.

typecheck 0 / lint 0-0 / build:verify 0-0.
2026-04-17 10:23:50 -04:00
ZacharyZhang-NY 9b45b12508 fix(onboarding): drop "Default" sentinel from model picker; auto-select real model
The CEO-runtime model dropdown on the Company onboarding step rendered
a {value:"", label:"默认 / Default"} sentinel as the first option, a
holdover from the adapter era when "" meant "let the connector pick".
Under pi-mono every connector carries a defaultModel and every run
must bind a concrete model id, so the sentinel is now misleading —
picking it left selectedModel empty and the wizard would advance
without a valid model.

- CompanyStep: drop the sentinel from the options array; the dropdown
  now shows only real models (or a single "Loading..." entry while
  the per-connector fetch is in flight).
- useConnectorModelSelection: when the connector's current model is
  not enabled, auto-select the connector's defaultModel if enabled,
  otherwise the first enabled model. An empty enabled list still
  falls back to "" so the CompanyStep hint UI behaves correctly.

Result: Fire Pass now shows "Kimi K2.5 Turbo (Fire Pass)" as the
sole option (pre-selected). Every other connector picks its catalog
default up-front.

typecheck 0 / lint 0-0 / build 0-0 / test:unit 508/508.
2026-04-17 09:54:46 -04:00
ZacharyZhang-NY e7e43bd0a6 fix(fireworks): route Fireworks models through resolveModel everywhere
pi-ai's getModel/getModels does not know about the Fireworks providers
(fireworks, fireworks-firepass); both live under our local model-resolver
because Fireworks speaks the Anthropic-compat endpoint with Bearer auth
at https://api.fireworks.ai/inference, not pi-ai's built-in catalog.

Three call sites were still hitting pi-ai directly and failing silently
for Fireworks:

1. connector-model-policy.ts — listProviderModels() caught the pi-ai
   throw and returned []. The "Fire Pass (CEO runtime)" card in the
   Team Models onboarding step therefore showed "暂无模型 / 已启用 0/0",
   blocking users on Fire Pass from continuing onboarding.

2. worker/worker-runner.ts — getModel() threw mid-run when the selected
   connector was Fireworks, so the worker could never actually execute
   an agent turn against Fire Pass or the curated Fireworks model set.
   Now uses resolveModel() + the Fireworks-specific Bearer header from
   resolveExtraStreamHeaders() so streamSimple hits the correct endpoint
   with the correct auth.

3. agent-runtime/cost-writer.ts — cost observation silently wrote
   amount_usd=null for Fireworks runs because getModel() threw inside
   the try/catch. Now resolves via resolveModel() so the Fireworks
   curated contextWindow/maxTokens are visible to calculateCost().

Verification: pnpm typecheck 0 / pnpm lint 0-0 / pnpm build:verify 0-0
/ pnpm test:unit 508/508.
2026-04-17 09:51:38 -04:00
ZacharyZhang-NY 84a3520ea8 fix(ipc): register credentials + oauth handlers in main runtime
The `registerCredentialIpcHandlers` and `registerOAuthIpcHandlers`
entry points existed in `ipc-credentials-handlers.ts` and
`ipc-oauth-handlers.ts` but were never called — `registerHandlers()`
in `main-runtime-support.ts` only wired `registerCoreHandlers` and
`registerDomainHandlers`. The result: every renderer call to
`credentials:list` / `credentials:save` / `credentials:remove` /
`credentials:test` / `oauth:start` / `oauth:cancel` /
`oauth:prompt-response` / `oauth:manual-code-response` crashed
with "No handler registered".

Wire both handler families against the PiRuntimeServices container
(credentialStore, credentialResolver, oauthLoginService) already
exposed via `serviceGraph.getPiRuntime()`. The refreshConnectorHealth
callback reuses the existing connectorHealthService so status
badges flip between `ready` and `auth_required` immediately after
a save/login.

typecheck 0 / lint 0-0 / build 0-0 / test:unit 508/508 preserved.
2026-04-17 09:44:46 -04:00
ZacharyZhang-NY e94939a562 test(connector-id): migrate fixtures and assertions to pi-mono ids
Replaces legacy adapter ids (codex_local / claude_local / gemini_local /
claude_compatible) across ~42 test files with pi-mono equivalents:
- codex_local → openai-codex
- claude_local → claude-pro
- gemini_local → gemini-cli
- claude_compatible → anthropic

Hand-rewrites where fixture semantics changed:
- connector-matching: TASK_TYPE_PREFERENCE ordering rebased (claude-pro
  first for code/content/management; google first for research)
- connector-model-policy: getModels(provider) from pi-ai instead of the
  deleted adapter.module.models array
- session-management + edge-case-session: adapter exemption removed;
  rotation now uniform under pi-mono
- ipc-core-admin-handlers: CSV compat model replaced with pi-ai anthropic
- connectors.spec: lookup by openai-codex id (catalog now starts with claude-pro)
- onboarding-model-pool: listProviderModels(provider) helper; label text
  changed to "ChatGPT Plus/Pro (Codex)"
- database integration: added vault insecure-fallback env + electron mock
- command-paths: uses new @main/connector-helpers normalizeCommandValue
- pi-mono-migrations: added `as string` casts for 3 negative-existence
  assertions verifying legacy ids were removed

Drops:
- pnpm-workspace.yaml packages: [] (was "packages/*"; directory empty)
- obsolete CONNECTOR_STRENGTHS import; .module.models probing

Verification:
- pnpm typecheck → 0 errors
- pnpm lint → 0 errors / 0 warnings
- pnpm build:verify → 0 errors / 0 warnings
- pnpm test:unit → 508/508 pass
- pnpm test:integration → 96/96 pass
- All 6 adapter hard gates pass (NOT FOUND / 0 matches / empty)
- pi-ai / pi-agent-core / pi-coding-agent all resolved @0.67.6
2026-04-17 02:36:53 -04:00
ZacharyZhang-NY 4de9cd0339 refactor(worker): use pi-mono Agent directly
Rewrites the utility-process worker to drive pi-agent-core's Agent class
against pi-ai models and pi-coding-agent tools. The entry file keeps the
queue and cancellation state, delegates runs to WorkerRunner, and routes
RPC responses through WorkerRpcClient so beforeToolCall/afterToolCall
approvals and prepareRun credential resolution travel back to main's
RuntimeBridge. Worker message schema gains `agent-event` + `rpc-request`
envelopes, and run-finished no longer depends on the deleted sessionCodec.
2026-04-17 02:21:12 -04:00
ZacharyZhang-NY 892476bd36 refactor(runtime): wire pi-runtime services and extend RuntimeBridge
Bootstraps CredentialStore/Resolver, OAuthLoginService, and RuntimeBridge
inside service-graph via the existing pi-runtime factory, and exposes the
bridge to worker-service for agent-event + rpc-request routing. Adds a
`prepareRun` RPC that resolves credentials, loads prior messages, and
registers the active run context in a single call. Session rotation drops
the adapter nativeContextManagement branch; run payloads now carry the
taskSessionId and executionMode the worker needs to drive pi-agent-core.
2026-04-17 02:21:04 -04:00
ZacharyZhang-NY 06a3ba603e refactor(connectors): remove adapter module references from services
Drops every `definition.module.*` call and legacy id hardcode (claude_local,
codex_local, gemini_local, claude_compat_*) from the connector services.
Health checks now evaluate stored credentials against the declarative auth
descriptor, model policy reads provider models via pi-ai, matching keys off
provider ids, and hire-hook logs activity without invoking an adapter hook.
Introduces a local normalizeCommandValue helper to replace the deleted
@agentcompany/adapter-utils/server-utils import.
2026-04-17 02:20:56 -04:00
ZacharyZhang-NY 4a120f4fc6 feat(settings): drive providers panel from pi-mono catalog
ProvidersPanel reads all 26 CONNECTOR_CATALOG entries and groups them by
auth kind (OAuth / API key / Azure / AWS / Vertex). ProviderRow
dispatches to the matching dedicated form component per auth kind. AWS,
Azure, Vertex forms rewritten with Tailwind classes and a shared field
style module so the Settings pane renders with the same aesthetic as the
rest of the app.
2026-04-17 02:19:56 -04:00
ZacharyZhang-NY 7fdd3c16bf feat(renderer): rewrite providers UI on pi-mono catalog shape
Onboarding ProvidersStep now reads the 26-entry CONNECTOR_CATALOG and
renders featured connectors (claude-pro, openai-codex, anthropic, openai,
amazon-bedrock) up front with a collapsible advanced list for the
remaining 21. Each auth kind gets a dedicated card component: OAuth
button flow, inline API-key form, and a cloud deep-link to Settings.
Delete legacy Claude/Codex/Gemini hardcoded cards and the compatible-API
slot rotation. Swap ModelManagement Settings panel for the new
ProvidersPanel driven by credentialsList IPC.
2026-04-17 02:16:35 -04:00
ZacharyZhang-NY 6a25379995 feat(shared): expose pi-mono connector catalog to renderer
Add @shared/connector-catalog.ts mirroring the 26-entry pi-mono catalog
from src/main/connector-definitions so renderer can drive provider UI
without importing main-process modules. Widen connectorInputSchema to
accept the new ConnectorId union (5 OAuth + 18 API key + 3 cloud).
2026-04-17 02:09:35 -04:00
ZacharyZhang-NY ea78c09615 refactor(connector): adapt buildDefaultConnectorRows to pi-mono shape
Pi-mono's ConnectorDefinition no longer carries defaultCommand,
configurationDoc, capabilityMatrix, or listModels. Synthesise sane
defaults for the legacy ConnectorRecord fields:

  - command defaults to empty (pi-mono has no CLI entrypoint)
  - capabilityMatrix collapses to a uniform pi-mono baseline
  - configurationDoc is generated from the auth descriptor using the
    existing buildOAuthDoc / buildApiKeyDoc / buildCloudDoc helpers

These columns stay in the schema so the UI surfaces that still read
them continue to function; the worker and resolver no longer branch on
capability flags since pi-mono handles dispatch uniformly.
2026-04-17 02:00:52 -04:00
ZacharyZhang-NY c2c54734a0 refactor(connector): rewrite catalog registry as pure pi-mono shape
Strips adapter module, defaultCommand, listModels, configurationDoc,
capabilityMatrix, and notes fields from the ConnectorDefinition type.
What remains is the declarative pi-mono shape: id, provider, label,
description, defaultModel, auth descriptor, onboardingFeatured, notes.

The three data files are imported and spread into the CONNECTORS array.
findConnectorDefinition + listFeaturedOnboardingConnectors stay in the
lookup module unchanged. Docs builders still provide buildOAuthDoc /
buildApiKeyDoc / buildCloudDoc for the Settings panel and are consumed
by connectors.ts when synthesising per-row configuration docs.

ConnectorAuth now uses `type` as the discriminator (legacy `kind` alias
removed — credential-resolver and ipc-credentials-handlers already keyed
off `type`).
2026-04-17 02:00:46 -04:00
ZacharyZhang-NY 77c92d0681 feat(connector): add pi-mono catalog data files
Pure-data declaration of the 26 pi-mono connectors split across three
files so each stays under the 400-line cap:

  - connector-definitions-data-oauth.ts   (5 OAuth providers)
  - connector-definitions-data-apikey.ts  (18 API-key providers)
  - connector-definitions-data-cloud.ts   (3 Cloud providers)

Each entry carries pi-ai provider id, default model, auth descriptor,
onboarding flag, and notes. Fireworks + Fire Pass are marked as locally
resolved (no pi-ai catalog entry) and share FIREWORKS_API_KEY.
2026-04-17 02:00:37 -04:00
ZacharyZhang-NY c088cf9e49 types(connector): expand ConnectorId to 26 pi-mono catalog ids
Replaces the 13 adapter-slot ids with the five OAuth / eighteen API-key /
three cloud ids that the pi-mono-driven catalog advertises. Downstream
worker, resolver, and database modules will be updated by follow-on
agents; this commit only redefines the type.
2026-04-17 01:57:47 -04:00
ZacharyZhang-NY d42d895f2a chore(lint): fix react-hooks/exhaustive-deps warnings
- App.tsx: replace per-field ui.navItems/ui.paletteQuery with the ui
  object so the memo captures every accessed field.
- ConsoleView.tsx: add eslint-disable for the logRevision dep; it is
  intentionally tracked to force ref re-evaluation.
2026-04-17 01:44:50 -04:00
ZacharyZhang-NY bc1f24d60c chore(lint): annotate SqliteRow as dynamic row shape
The any type is load-bearing here: callers destructure arbitrary SQL
columns. Add an inline eslint-disable with justification instead of
propagating a typing change across all DB modules.
2026-04-17 01:44:45 -04:00
ZacharyZhang-NY 71791825ce chore(lint): remove unused vars and imports
- agents-crud: drop unused roleLevel local + inferRoleLevel import
- agents-hierarchy: prefix unused builder params with _
- company-settings: drop InboxItem import, prefix unused builder params
- worker-message-handler: drop unused WorkerServiceDependencies import
2026-04-17 01:44:40 -04:00
ZacharyZhang-NY aba3ccd275 fix(schema): guard migration 28 indexes behind tableExists
Migration 28 (add_snapshot_hot_path_indexes) referenced task_comments,
documents, meetings, sprints, agent_messages, activity — all tables
created by ensureOptionalColumns() which runs AFTER runMigrations() on
a fresh DB. Converted from sql-string migration to fn-based so each
index is gated by tableExists(); safe on both fresh and migrated DBs.

Also updated tests/unit/selective-ipc.test.ts exhaustive switch to
include the 7 new DesktopEvent variants added in ef90a58.
2026-04-17 01:36:56 -04:00
ZacharyZhang-NY 70c2a3aa9e fix(renderer): type SidebarView t prop as TranslationFn
`t` is invoked with a two-arg `(key, fallback)` signature elsewhere;
use the shared `TranslationFn` type so those call sites compile.
2026-04-17 01:30:16 -04:00
ZacharyZhang-NY cad17b4d45 fix(credentials): close resolver switch and guard missing provider/auth
- credential-resolver.resolve: throw explicit CREDENTIAL_INVALID when
  the connector has no auth schema, and add a default branch so the
  switch has a definitive return path for every auth kind
- credential-resolver api_key branch: guard definition.provider being
  unset before calling pi-ai's getEnvApiKey
- cost-writer: only attempt cost lookup when definition.provider is
  defined; adapter-only connectors still write an unattributed row
2026-04-17 01:28:37 -04:00
ZacharyZhang-NY bee5535349 fix(credentials): guard optional auth/provider when resolving credentials
- oauth-login-service.start: require definition.auth to be present and
  oauth kind before dispatching; captures oauthId in a local so the rest
  of the flow does not re-assert the nullable chain
- ipc-credentials-handlers save: reject connectors without an auth
  schema instead of crashing on property access
- ipc-credentials-handlers test: require provider and defaultModel to be
  set before calling into pi-ai, returning a diagnostic result otherwise
2026-04-17 01:28:26 -04:00
ZacharyZhang-NY 2b63588604 feat(db): wire sessionEntries + credentialsTable and add migration 32
- Expose buildSessionEntryMethods and buildCredentialMethods on
  AppDatabaseBase as public readonly members so agent-runtime and
  credential-store can access them via db.sessionEntries /
  db.credentialsTable
- Add idempotent schema migration v32 creating session_entries and
  credentials tables plus supporting indexes; uses CREATE TABLE IF NOT
  EXISTS so existing profile DBs upgrade safely without destructive ops
2026-04-17 01:28:20 -04:00
ZacharyZhang-NY 70cdb6838d feat(connectors): extend ConnectorDefinition with provider/auth/onboarding
- Add PiOAuthProviderId literal type covering pi-ai's built-in OAuth
  providers (anthropic, openai-codex, github-copilot, gemini-cli,
  antigravity)
- Add optional ConnectorDefinition fields: provider (pi-ai provider id),
  auth (ConnectorAuth with kind/type/provider/oauthId/envKey), and
  onboardingFeatured
- Decorate built-in CONNECTORS (codex_local, claude_local, gemini_local,
  claude-compat slots) with their pi-ai provider id, auth schema, and
  onboarding flag so credential-resolver and oauth-login-service can
  dispatch without changing execute/module wiring
- Re-export CONNECTORS, findConnectorDefinition, and
  listFeaturedOnboardingConnectors from main/connectors so consumers
  (including tests) import from a single module
2026-04-17 01:28:13 -04:00
ZacharyZhang-NY ef90a58fa2 types(shared): add credentials/oauth channels, events, and desktop-api
- Add IPC_CHANNELS entries for credentials list/save/remove/test and
  oauth start/cancel/prompt/manual-code
- Extend DesktopEvent union with oauth:*, credentials-changed, and
  agent-event variants used by pi-mono runtime and settings UI
- Extend DesktopApi CredentialsApi with listCredentials / saveCredential
  / removeCredential / testCredential and OAuth submit helpers
2026-04-17 01:28:06 -04:00
ZacharyZhang-NY 1f310a121e i18n(automation): localize RuleEditor and WorkflowEditor form strings
Adds ~40 automation.ruleEditor.* and automation.workflowEditor.* keys
to en.ts + zh.ts (labels, placeholders, error messages, action labels).
RuleFormModal and WorkflowFormModal now route every hardcoded English
string through useT(), including validation errors and modal titles.

Closes remaining Z-B i18n work after the prompt-builder locale
dispatch (cf92e0c), dept-keywords typing (a78bdb9), and sidebar/
formatters/notification/skills i18n landed earlier.
2026-04-17 01:13:19 -04:00
ZacharyZhang-NY a78bdb9b02 refactor(automation): type DEPARTMENT_SKILL_KEYWORDS with DepartmentId enum
Replaces Record<string, string[]> with Record<DepartmentId, string[]>
so future edits to the department taxonomy trigger TS errors for any
keyword map that drifts. Cast at the lookup site reflects the fact
that agent.department is a free-form string column that may hold
legacy or custom values.
2026-04-17 01:10:49 -04:00
ZacharyZhang-NY cf92e0c646 refactor(prompt-builder): locale-dispatch every section for zh/en parity
Split each prompt section into parallel .en.md/.zh.md bundles (sops, api-docs,
ceo-modes, department-guidelines) and mirrored messages/{operating,system}-{en,zh}.ts
modules for the inline identity/culture/rules text that had stayed as hard-coded
English template literals. Every loader now resolves a locale via a single
shared helper so CEO and IC prompts come out fully Chinese when locale=zh and
fully English otherwise, removing the need for the trailing "请记住:全程使用中文"
language reminder.
2026-04-17 00:01:34 -04:00
ZacharyZhang-NY e1f70c7f9c refactor(prompt-builder): split Important Rules into Context + Operating Style + Critical Rules
- Previous section tangled ids, request headers, operating hints and 3
  CRITICAL bullets in one bullet list
- Replace with three clearly scoped sections:
  # Context (company/agent/run ids, single place)
  # Operating Style (conciseness + follow-up + structured summary)
  # Critical Rules (numbered 1-3: scope lockdown, workdir lockdown,
    must-call-API)
- All original CRITICAL concerns (MCP/TaskManager ban, no-cd, action
  mandate) preserved verbatim; no behavioural drift
2026-04-16 23:38:41 -04:00
ZacharyZhang-NY d75389c418 refactor(prompt-builder): convert 11-key wake reason map to data table
- New src/main/prompt-builder/wake-reasons/en.ts: WAKE_REASONS record of
  { title, steps(vars) } entries + renderWakeReason() formatter that
  numbers the steps and composes the final block
- buildTaskPrompt in prompt-builder/index.ts collapses 100-line inline
  reasonMap into a single renderWakeReason call
- index.ts shrinks from 161 to 77 lines; each wake reason's semantic
  content (title text + numbered action steps + embedded curl hints)
  preserved verbatim
2026-04-16 23:37:42 -04:00
ZacharyZhang-NY 75022f82c5 refactor(renderer): route all Phosphor icon imports through ui/icons barrel
Create src/renderer/components/ui/icons.ts as the single re-export point
for every Phosphor icon the renderer touches, then rewrite the 95 files
that previously imported directly from "@phosphor-icons/react" to pull
from the relative-path-to-barrel instead. The TitleBar commit earlier
in this series already used ui/icons; this commit extends the pattern
to the rest of the renderer.

Benefits now wired in:
  - one location where bundle tree-shaking can be reasoned about,
  - typos like Briefcase vs BriefCase show up against a finite list,
  - re-theming or swapping icon sets is a one-file edit,
  - a lint rule that flags raw @phosphor-icons/react imports can be
    added later without mass-rewriting call sites.

The barrel also re-exports the `Icon` type so call sites that type
icon props against the Phosphor component type work unchanged.

Test count stays at 363 passing; typecheck stays at 156 errors.
2026-04-16 23:37:35 -04:00
ZacharyZhang-NY 364f1683e3 refactor(prompt-builder): extract 7 department guidelines to markdown
- operating-instructions.ts buildDepartmentSection: replace 120-line
  if/else chain with a department-to-markdown lookup table
- New src/main/prompt-builder/department-guidelines/ contains:
  engineering, finance, hr, marketing, sales, customer_support, operations
- Each file uses {{companyId}} placeholder, substituted at render time
- operating-instructions.ts trimmed from 384 to 285 lines while
  preserving every guideline verbatim
2026-04-16 23:36:09 -04:00
ZacharyZhang-NY d513497341 i18n(skills): localise SkillsSection strings
SkillsSection had nine hardcoded English strings (header, filter
placeholder/aria-label, empty-state copy, button labels). Move them to
skills.* keys in en.ts/zh.ts and swap the component to useT().
2026-04-16 23:35:21 -04:00
ZacharyZhang-NY 2bd47a601a refactor(service-graph): eagerly construct leaf services in init()
Moves skill, budget-enforcement, and session-management service
construction to the top of service-graph init(), so the three
getOrCreate* getters are pure readers that throw if called before
init. This also fixes a duplicate-allocation bug in the orchestration
listRuntimeSkillEntries closure, which was building a second
SkillService instance instead of reusing the shared one.

The outer getOrCreate* API surface stays intact for
main-runtime-support.ts callers. The teardown setTimeout(app.exit,
3000) is left in place because worker CLI child processes keep the
event loop alive; replacing it needs a full Disposable chain refactor
that conflicts with in-progress pi-runtime integration work.
2026-04-16 23:35:14 -04:00
ZacharyZhang-NY 6e4fd078d9 refactor(prompt-builder): extract API docs into markdown sections
- Split 366-line api-section.ts into 11 category markdown files under
  src/main/prompt-builder/api-docs/ (header, agent-control, tasks,
  goals-projects, approvals, messages, files, knowledge, meetings,
  agents, sprints)
- api-section.ts reduced to ~45 lines: imports each section via ?raw,
  substitutes {{apiUrl}}/{{companyId}}/{{agentId}}/{{runId}}/{{connectorIds}},
  joins sections and appends social media addendum
- Every endpoint signature, body schema, and curl example preserved
  verbatim so LLM instruction surface is unchanged
2026-04-16 23:34:20 -04:00
ZacharyZhang-NY a2a90f00e6 refactor(bootstrap): extract bootstrap-application into orchestrator + modules
Splits the 391-line bootstrapApplication god function into a thin
orchestrator plus 7 focused modules under src/main/bootstrap/:
prepare-logger, prepare-database, prepare-services (service graph +
ipc wiring), wire-api-server (14-callback dictionary), recover-
scheduled-posts, run-startup-health-checks, recover-interrupted-tasks
(crash notification + clean-shutdown task resumption). Original
startup order, before-quit cleanup, and error handling are preserved;
the entry file drops to 153 lines.
2026-04-16 23:34:13 -04:00
ZacharyZhang-NY dd007760b8 refactor(ui): promote BudgetBar and InlineConfirmDelete to shared ui/
BudgetBar and ConfirmDelete were only sitting in organization/helpers.tsx
but have no organization-specific behaviour. Move them under
components/ui/ and keep the old exports as re-exports so existing
importers continue to resolve. HeartbeatSection stays in helpers.tsx
because it owns agent-specific heartbeat IPC.
2026-04-16 23:34:12 -04:00
ZacharyZhang-NY 61aba41e77 refactor(renderer): rename EntityWorkspace to TwoPaneLayout for clarity 2026-04-16 23:33:55 -04:00
ZacharyZhang-NY 933fcf27d0 refactor(runs): extract useRunLogs hook from RunCenter
RunCenter had three useEffects juggling log-chunk loading, tailing, and
older-chunk fetches. Move the whole lifecycle into useRunLogs, which
uses a single effect + AbortController to scope every IPC call to the
current run and pauses polling while document.hidden.
2026-04-16 23:32:02 -04:00
ZacharyZhang-NY 0c9d8269c1 refactor(dashboard): consolidate BudgetAlertBanner dual source into helper 2026-04-16 23:31:58 -04:00
ZacharyZhang-NY c6935ff983 refactor(ui): move AttentionRow to ui and reuse in Inbox 2026-04-16 23:29:58 -04:00
ZacharyZhang-NY 279af3b034 refactor(database): expose domain modules as public readonly fields
Changes the AppDatabaseBase module slots (tasks, agents, runs, ...)
from protected to public readonly so new call sites can reach them
directly as db.tasks.x / db.agents.x. The 156 pass-through methods on
AppDatabase remain untouched, so all existing callers keep working;
this is the first step of a two-part migration to eventually drop
the pass-through layer.
2026-04-16 23:29:07 -04:00