@pinagent/react-native 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.
@@ -0,0 +1,109 @@
1
+ import { IncomingMessage, Server, ServerResponse } from "node:http";
2
+ import { WebSocketServer } from "ws";
3
+
4
+ //#region ../agent-runner/dist/index.d.ts
5
+ //#endregion
6
+ //#region src/agent-permission.d.ts
7
+ type SpawnAgentMode = 'worktree' | 'inline' | false;
8
+ /**
9
+ * Resolve the spawn mode from env. The new default (V2) is `'inline'` —
10
+ * SDK-backed per-submit agent with streaming back to the widget. Worktree
11
+ * mode is opt-in; `'off'` (or the legacy `'false'`) disables spawning so
12
+ * channel-mode / pull-mode setups don't get a redundant agent per submit.
13
+ */
14
+ /**
15
+ * Build a `noServer` WebSocket endpoint to hand to a host that owns its own
16
+ * HTTP server and routes the `upgrade` event by pathname — notably Metro's
17
+ * `config.server.websocketEndpoints` (React Native / Expo).
18
+ *
19
+ * Unlike {@link startWsServer}, this binds no port: the caller's dev server
20
+ * (Metro) already listens, performs the HTTP upgrade, and dispatches matching
21
+ * requests here via `handleUpgrade`. That means RN streaming rides the *same*
22
+ * host:port the widget already talks to for `POST /__pinagent/feedback`, so a
23
+ * physical device needs no second port and no port discovery.
24
+ *
25
+ * Each accepted socket is wired to the same {@link attachConnection} the web
26
+ * path uses — identical wire protocol, bus subscription, and worktree
27
+ * controls. We also start the project-event fan-out and relay (idempotent,
28
+ * singleton-guarded) so worktree Land/Discard and cloud mode behave the same.
29
+ */
30
+ declare function createPinagentWsEndpoint(): WebSocketServer;
31
+ //#endregion
32
+ //#region src/server/metro-middleware.d.ts
33
+ type Handler = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
34
+ interface PinagentMiddlewareOpts {
35
+ /** Project root — where `.pinagent/` lives. Pass `__dirname`. */
36
+ projectRoot: string;
37
+ /**
38
+ * Agent spawn mode, same semantics as the Vite plugin:
39
+ * `false` (file only), `'inline'`, or `'worktree'`. Defaults to
40
+ * `'inline'`.
41
+ */
42
+ spawnMode?: SpawnAgentMode;
43
+ /**
44
+ * Optional explicit API key for spawned agent runs, same semantics as the
45
+ * Vite plugin's `apiKey`.
46
+ *
47
+ * Pinagent never reads `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` from the
48
+ * environment on its own — a key exported in your shell for other tools must
49
+ * not get billed (or, if stale, fail the run with "Invalid API key") just
50
+ * because pinagent happened to inherit it. When you leave this unset, runs
51
+ * authenticate against your agentic subscription (Claude Code, or Codex's
52
+ * ChatGPT login when using the CLI provider).
53
+ *
54
+ * Set it only when you deliberately want a raw key used, e.g.
55
+ * `pinagentMiddleware({ projectRoot: __dirname, apiKey: process.env.MY_KEY })`.
56
+ * For the default Claude provider it's passed as the Anthropic key; for the
57
+ * bring-your-own CLI provider it's supplied to the wrapped CLI as both
58
+ * `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`. Bridged to the runner via the
59
+ * `PINAGENT_AGENT_API_KEY` env var (RN has no dock, so the option/env is the
60
+ * whole story — there's no runtime Connections store to take precedence).
61
+ */
62
+ apiKey?: string;
63
+ }
64
+ interface PinagentMiddleware {
65
+ (req: IncomingMessage, res: ServerResponse, next: () => void): void;
66
+ /** Compose: run pinagent routes first, then `next` for everything else. */
67
+ chain(next: Handler): Handler;
68
+ }
69
+ declare function pinagentMiddleware(opts: PinagentMiddlewareOpts): PinagentMiddleware;
70
+ //#endregion
71
+ //#region src/server/ws-endpoint.d.ts
72
+ interface PinagentWsEndpointsOpts {
73
+ /**
74
+ * Project root — where `.pinagent/` lives. Pass `__dirname`, the same value
75
+ * given to `pinagentMiddleware`. The agent run records events keyed on this
76
+ * root; the WS server's bus subscription otherwise resolves the root from
77
+ * `PINAGENT_PROJECT_ROOT` (falling back to `process.cwd()`). Metro's cwd is
78
+ * usually the project dir, but we pin the env var so streaming always reads
79
+ * the same `.pinagent/db.sqlite` the feedback middleware writes to.
80
+ */
81
+ projectRoot: string;
82
+ }
83
+ /**
84
+ * Returns the `{ [path]: ws.Server }` map to spread into Metro's
85
+ * `config.server.websocketEndpoints`. Mounts the Pinagent stream at
86
+ * `/__pinagent/ws`.
87
+ */
88
+ declare function pinagentWebsocketEndpoints(opts: PinagentWsEndpointsOpts): Record<string, ReturnType<typeof createPinagentWsEndpoint>>;
89
+ /**
90
+ * Idempotently mount `/__pinagent/ws` on a live HTTP server, regardless of
91
+ * whether the host honors `config.server.websocketEndpoints`.
92
+ *
93
+ * Expo's dev server registers a single `upgrade` listener that destroys any
94
+ * path it doesn't know, so simply *adding* a second listener races with that
95
+ * destroy. Instead we take the listener over: capture whatever `upgrade`
96
+ * listeners are already attached (Metro's `/hot`, Expo's devtools/debugger
97
+ * sockets, …), remove them, and install one router that handles
98
+ * `/__pinagent/ws` itself and delegates every other path back to the captured
99
+ * listeners untouched. HMR and the rest keep working; our path no longer gets
100
+ * destroyed out from under us.
101
+ *
102
+ * Called lazily from `pinagentMiddleware` with `req.socket.server` — by the
103
+ * time any HTTP request reaches the middleware the dev server is listening and
104
+ * its own `upgrade` listener is already registered, so the capture is complete.
105
+ */
106
+ declare function ensurePinagentUpgrade(server: Server): void;
107
+ //#endregion
108
+ export { type PinagentMiddleware, type PinagentMiddlewareOpts, type PinagentWsEndpointsOpts, ensurePinagentUpgrade, pinagentMiddleware, pinagentWebsocketEndpoints };
109
+ //# sourceMappingURL=server.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.cts","names":["z","ZodObject","baseBranch","ZodString","worktreeRetentionDays","ZodNumber","perConversationCapUsd","monthlyBudgetUsd","ZodNullable","permissionMode","ZodEnum","auto","approve","allowedBranchPatterns","ZodArray","core","$strip","infer","ProjectSettingsSchema","ZodOptional","ProjectSettingsPatchSchema","ProjectSettings","projectRoot","constructor","path","read","Promise","patch","ProjectSettingsPatch","NodeJS","ProcessEnv","env","SpawnAgentMode","PermissionMode$1","PermissionMode","mode","RegExp","file","line","col","selector","clickX","clickY","component","AdditionalAnchorSchema","comment","loc","url","viewport","w","h","userAgent","screenshot","createdAt","additionalAnchors","componentPath","instance","index","total","fingerprint","FeedbackInputSchema","pending","fixed","wontfix","deferred","StatusSchema","none","active","landed","discarded","WorktreeStateSchema","id","AdditionalAnchor","instanceIndex","instanceTotal","instanceFingerprint","status","Status","note","commitSha","agentSessionId","branch","worktreePath","worktreeState","WorktreeState","title","archived","updatedAt","resolvedAt","messageCount","totalCostUsd","apiKeySource","isRunning","ZodBoolean","PatchSchema","root","feedbackDir","screenshotsDir","legacyImportDone","db","ensureDirs","maybeImportLegacy","insertRecord","create","FeedbackInput","input","FeedbackRecord","list","readApiKeySource","computeConversationCost","computeMonthlySpend","Date","month","listMessages","AgentEvent","readScreenshotBase64","rec","patchWithDiff","Patch","record","previousStatus","atomicWriteBytes","target","ok","conflicts","error","feedbackId","logPath","LandResult","reopened","failed","feedbackIds","BulkReopenResult","filesChanged","additions","deletions","baseRef","WorktreeStats","diff","truncated","WorktreeDiff","feedback","AgentContext","ctx","content","McpSdkServerConfigWithInstance","askId","answer","reason","conversationId","actor","AuditActor","action","AuditAction","payload","Record","limit","offset","RecordAuditEventInput","ListAuditEventsOpts","opts","AuditEventRecord","name","conversationTitle","lastActivity","state","diskMb","BranchRecord","PruneResult","port","reused","ServeBranchResult","pruned","retentionDays","BulkPruneBodySchema","BulkPruneResult","PruneStaleResult","publish","event","subscribe","BusSubscriber","sub","markFinished","SqliteEventBus","externallyModified","preview","ChangeRecord","login","token","GithubValidation","key","AnthropicValidation","ids","BulkUpdateBodySchema","BulkReopenBodySchema","ApplyPatchResult","updated","skipped","BulkArchiveResult","editor","command","OpenInEditorResult","dir","isDir","entries","FileEntry","query","ListFilesResult","stdout","cwd","HistoryStatusFilter","matchedFields","MatchedField","snippet","HistorySearchOpts","HistorySearchHit","branchName","description","prUrl","branchPushed","manualCompareUrl","files","ComposeOpts","ComposeResult","targetFile","prompt","isInitial","AgentPermissionMode","resume","abortSignal","AbortSignal","events","log","sessionId","isResult","resultFooter","run","AgentRunRequest","req","AsyncIterable","ProviderRunItem","AgentProvider","ProviderId","number","body","conversationIds","PullRequestRecord","minBackoffMs","maxBackoffMs","connect","WebSocket","attach","socket","schedule","fn","ms","msg","close","origin","attempt","min","max","RelayClientOptions","RelayClientHandle","ZodDefault","github","anthropic","SecretsFileSchema","connected","keySet","SecretsFile","Partial","setGithub","clearGithub","setAnthropic","clearAnthropic","getGithubToken","getAnthropicKey","presentable","PresentableConnections","text","PrSummary","added","deleted","WorkingCopyFileStatus","isDefaultBranch","WorkingCopyFile","ahead","behind","hasUpstream","dirty","pr","WorkingCopyPrRef","WorkingCopyStatus","WorktreeServerInfo","override","args","ServeResult","wss","WebSocketServer","httpServer","Server","ServerHandle"],"sources":["../../agent-runner/dist/index.d.ts","../src/server/metro-middleware.ts","../src/server/ws-endpoint.ts"],"mappings":";;;;;;KA4CK,cAAA;;;;;;;;;;;;;;;;;;;;;;;iBAi2CY,wBAAA,IAA4B,eAAe;;;KCr2CvD,OAAA,IAAW,GAAA,EAAK,eAAA,EAAiB,GAAA,EAAK,cAAc,EAAE,IAAA;AAAA,UAE1C,sBAAA;;EAEf,WAAA;EDAG;;;;AAAc;ECMjB,SAAA,GAAY,cAAc;ED21Ca;;;AAAmB;;;;AC32C5B;;;;;;;;;;AAM2C;AAE3E;EA4BE,MAAA;AAAA;AAAA,UAGe,kBAAA;EAAA,CACd,GAAA,EAAK,eAAA,EAAiB,GAAA,EAAK,cAAA,EAAgB,IAAA;EAxB5C;EA0BA,KAAA,CAAM,IAAA,EAAM,OAAA,GAAU,OAAA;AAAA;AAAA,iBAGR,kBAAA,CAAmB,IAAA,EAAM,sBAAA,GAAyB,kBAAkB;;;UChCnE,uBAAA;ED6BH;;;;;;;;ECpBZ,WAAW;AAAA;;;;;ADoBkB;iBCZf,0BAAA,CACd,IAAA,EAAM,uBAAA,GACL,MAAA,SAAe,UAAA,QAAkB,wBAAA;;;;;;;;ADagD;;;;AChCpF;;;;AASa;AAQb;iBA+BgB,qBAAA,CAAsB,MAAc,EAAN,MAAM"}
@@ -0,0 +1,110 @@
1
+ import { z } from "zod";
2
+ import { WebSocket, WebSocketServer } from "ws";
3
+ import { IncomingMessage, Server, ServerResponse } from "node:http";
4
+
5
+ //#region ../agent-runner/dist/index.d.ts
6
+ //#endregion
7
+ //#region src/agent-permission.d.ts
8
+ type SpawnAgentMode = 'worktree' | 'inline' | false;
9
+ /**
10
+ * Resolve the spawn mode from env. The new default (V2) is `'inline'` —
11
+ * SDK-backed per-submit agent with streaming back to the widget. Worktree
12
+ * mode is opt-in; `'off'` (or the legacy `'false'`) disables spawning so
13
+ * channel-mode / pull-mode setups don't get a redundant agent per submit.
14
+ */
15
+ /**
16
+ * Build a `noServer` WebSocket endpoint to hand to a host that owns its own
17
+ * HTTP server and routes the `upgrade` event by pathname — notably Metro's
18
+ * `config.server.websocketEndpoints` (React Native / Expo).
19
+ *
20
+ * Unlike {@link startWsServer}, this binds no port: the caller's dev server
21
+ * (Metro) already listens, performs the HTTP upgrade, and dispatches matching
22
+ * requests here via `handleUpgrade`. That means RN streaming rides the *same*
23
+ * host:port the widget already talks to for `POST /__pinagent/feedback`, so a
24
+ * physical device needs no second port and no port discovery.
25
+ *
26
+ * Each accepted socket is wired to the same {@link attachConnection} the web
27
+ * path uses — identical wire protocol, bus subscription, and worktree
28
+ * controls. We also start the project-event fan-out and relay (idempotent,
29
+ * singleton-guarded) so worktree Land/Discard and cloud mode behave the same.
30
+ */
31
+ declare function createPinagentWsEndpoint(): WebSocketServer;
32
+ //#endregion
33
+ //#region src/server/metro-middleware.d.ts
34
+ type Handler = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
35
+ interface PinagentMiddlewareOpts {
36
+ /** Project root — where `.pinagent/` lives. Pass `__dirname`. */
37
+ projectRoot: string;
38
+ /**
39
+ * Agent spawn mode, same semantics as the Vite plugin:
40
+ * `false` (file only), `'inline'`, or `'worktree'`. Defaults to
41
+ * `'inline'`.
42
+ */
43
+ spawnMode?: SpawnAgentMode;
44
+ /**
45
+ * Optional explicit API key for spawned agent runs, same semantics as the
46
+ * Vite plugin's `apiKey`.
47
+ *
48
+ * Pinagent never reads `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` from the
49
+ * environment on its own — a key exported in your shell for other tools must
50
+ * not get billed (or, if stale, fail the run with "Invalid API key") just
51
+ * because pinagent happened to inherit it. When you leave this unset, runs
52
+ * authenticate against your agentic subscription (Claude Code, or Codex's
53
+ * ChatGPT login when using the CLI provider).
54
+ *
55
+ * Set it only when you deliberately want a raw key used, e.g.
56
+ * `pinagentMiddleware({ projectRoot: __dirname, apiKey: process.env.MY_KEY })`.
57
+ * For the default Claude provider it's passed as the Anthropic key; for the
58
+ * bring-your-own CLI provider it's supplied to the wrapped CLI as both
59
+ * `ANTHROPIC_API_KEY` and `OPENAI_API_KEY`. Bridged to the runner via the
60
+ * `PINAGENT_AGENT_API_KEY` env var (RN has no dock, so the option/env is the
61
+ * whole story — there's no runtime Connections store to take precedence).
62
+ */
63
+ apiKey?: string;
64
+ }
65
+ interface PinagentMiddleware {
66
+ (req: IncomingMessage, res: ServerResponse, next: () => void): void;
67
+ /** Compose: run pinagent routes first, then `next` for everything else. */
68
+ chain(next: Handler): Handler;
69
+ }
70
+ declare function pinagentMiddleware(opts: PinagentMiddlewareOpts): PinagentMiddleware;
71
+ //#endregion
72
+ //#region src/server/ws-endpoint.d.ts
73
+ interface PinagentWsEndpointsOpts {
74
+ /**
75
+ * Project root — where `.pinagent/` lives. Pass `__dirname`, the same value
76
+ * given to `pinagentMiddleware`. The agent run records events keyed on this
77
+ * root; the WS server's bus subscription otherwise resolves the root from
78
+ * `PINAGENT_PROJECT_ROOT` (falling back to `process.cwd()`). Metro's cwd is
79
+ * usually the project dir, but we pin the env var so streaming always reads
80
+ * the same `.pinagent/db.sqlite` the feedback middleware writes to.
81
+ */
82
+ projectRoot: string;
83
+ }
84
+ /**
85
+ * Returns the `{ [path]: ws.Server }` map to spread into Metro's
86
+ * `config.server.websocketEndpoints`. Mounts the Pinagent stream at
87
+ * `/__pinagent/ws`.
88
+ */
89
+ declare function pinagentWebsocketEndpoints(opts: PinagentWsEndpointsOpts): Record<string, ReturnType<typeof createPinagentWsEndpoint>>;
90
+ /**
91
+ * Idempotently mount `/__pinagent/ws` on a live HTTP server, regardless of
92
+ * whether the host honors `config.server.websocketEndpoints`.
93
+ *
94
+ * Expo's dev server registers a single `upgrade` listener that destroys any
95
+ * path it doesn't know, so simply *adding* a second listener races with that
96
+ * destroy. Instead we take the listener over: capture whatever `upgrade`
97
+ * listeners are already attached (Metro's `/hot`, Expo's devtools/debugger
98
+ * sockets, …), remove them, and install one router that handles
99
+ * `/__pinagent/ws` itself and delegates every other path back to the captured
100
+ * listeners untouched. HMR and the rest keep working; our path no longer gets
101
+ * destroyed out from under us.
102
+ *
103
+ * Called lazily from `pinagentMiddleware` with `req.socket.server` — by the
104
+ * time any HTTP request reaches the middleware the dev server is listening and
105
+ * its own `upgrade` listener is already registered, so the capture is complete.
106
+ */
107
+ declare function ensurePinagentUpgrade(server: Server): void;
108
+ //#endregion
109
+ export { type PinagentMiddleware, type PinagentMiddlewareOpts, type PinagentWsEndpointsOpts, ensurePinagentUpgrade, pinagentMiddleware, pinagentWebsocketEndpoints };
110
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","names":["z","ZodObject","baseBranch","ZodString","worktreeRetentionDays","ZodNumber","perConversationCapUsd","monthlyBudgetUsd","ZodNullable","permissionMode","ZodEnum","auto","approve","allowedBranchPatterns","ZodArray","core","$strip","infer","ProjectSettingsSchema","ZodOptional","ProjectSettingsPatchSchema","ProjectSettings","projectRoot","constructor","path","read","Promise","patch","ProjectSettingsPatch","NodeJS","ProcessEnv","env","SpawnAgentMode","PermissionMode$1","PermissionMode","mode","RegExp","file","line","col","selector","clickX","clickY","component","AdditionalAnchorSchema","comment","loc","url","viewport","w","h","userAgent","screenshot","createdAt","additionalAnchors","componentPath","instance","index","total","fingerprint","FeedbackInputSchema","pending","fixed","wontfix","deferred","StatusSchema","none","active","landed","discarded","WorktreeStateSchema","id","AdditionalAnchor","instanceIndex","instanceTotal","instanceFingerprint","status","Status","note","commitSha","agentSessionId","branch","worktreePath","worktreeState","WorktreeState","title","archived","updatedAt","resolvedAt","messageCount","totalCostUsd","apiKeySource","isRunning","ZodBoolean","PatchSchema","root","feedbackDir","screenshotsDir","legacyImportDone","db","ensureDirs","maybeImportLegacy","insertRecord","create","FeedbackInput","input","FeedbackRecord","list","readApiKeySource","computeConversationCost","computeMonthlySpend","Date","month","listMessages","AgentEvent","readScreenshotBase64","rec","patchWithDiff","Patch","record","previousStatus","atomicWriteBytes","target","ok","conflicts","error","feedbackId","logPath","LandResult","reopened","failed","feedbackIds","BulkReopenResult","filesChanged","additions","deletions","baseRef","WorktreeStats","diff","truncated","WorktreeDiff","feedback","AgentContext","ctx","content","McpSdkServerConfigWithInstance","askId","answer","reason","conversationId","actor","AuditActor","action","AuditAction","payload","Record","limit","offset","RecordAuditEventInput","ListAuditEventsOpts","opts","AuditEventRecord","name","conversationTitle","lastActivity","state","diskMb","BranchRecord","PruneResult","port","reused","ServeBranchResult","pruned","retentionDays","BulkPruneBodySchema","BulkPruneResult","PruneStaleResult","publish","event","subscribe","BusSubscriber","sub","markFinished","SqliteEventBus","externallyModified","preview","ChangeRecord","login","token","GithubValidation","key","AnthropicValidation","ids","BulkUpdateBodySchema","BulkReopenBodySchema","ApplyPatchResult","updated","skipped","BulkArchiveResult","editor","command","OpenInEditorResult","dir","isDir","entries","FileEntry","query","ListFilesResult","stdout","cwd","HistoryStatusFilter","matchedFields","MatchedField","snippet","HistorySearchOpts","HistorySearchHit","branchName","description","prUrl","branchPushed","manualCompareUrl","files","ComposeOpts","ComposeResult","targetFile","prompt","isInitial","AgentPermissionMode","resume","abortSignal","AbortSignal","events","log","sessionId","isResult","resultFooter","run","AgentRunRequest","req","AsyncIterable","ProviderRunItem","AgentProvider","ProviderId","number","body","conversationIds","PullRequestRecord","minBackoffMs","maxBackoffMs","connect","WebSocket","attach","socket","schedule","fn","ms","msg","close","origin","attempt","min","max","RelayClientOptions","RelayClientHandle","ZodDefault","github","anthropic","SecretsFileSchema","connected","keySet","SecretsFile","Partial","setGithub","clearGithub","setAnthropic","clearAnthropic","getGithubToken","getAnthropicKey","presentable","PresentableConnections","text","PrSummary","added","deleted","WorkingCopyFileStatus","isDefaultBranch","WorkingCopyFile","ahead","behind","hasUpstream","dirty","pr","WorkingCopyPrRef","WorkingCopyStatus","WorktreeServerInfo","override","args","ServeResult","wss","WebSocketServer","httpServer","Server","ServerHandle"],"sources":["../../agent-runner/dist/index.d.ts","../src/server/metro-middleware.ts","../src/server/ws-endpoint.ts"],"mappings":";;;;;;;KA4CK,cAAA;;;;;;;;;;;;;;;;;;;;;;;iBAi2CY,wBAAA,IAA4B,eAAe;;;KCr2CvD,OAAA,IAAW,GAAA,EAAK,eAAA,EAAiB,GAAA,EAAK,cAAc,EAAE,IAAA;AAAA,UAE1C,sBAAA;;EAEf,WAAA;EDAG;;;;AAAc;ECMjB,SAAA,GAAY,cAAc;ED21Ca;;;AAAmB;;;;AC32C5B;;;;;;;;;;AAM2C;AAE3E;EA4BE,MAAA;AAAA;AAAA,UAGe,kBAAA;EAAA,CACd,GAAA,EAAK,eAAA,EAAiB,GAAA,EAAK,cAAA,EAAgB,IAAA;EAxB5C;EA0BA,KAAA,CAAM,IAAA,EAAM,OAAA,GAAU,OAAA;AAAA;AAAA,iBAGR,kBAAA,CAAmB,IAAA,EAAM,sBAAA,GAAyB,kBAAkB;;;UChCnE,uBAAA;ED6BH;;;;;;;;ECpBZ,WAAW;AAAA;;;;;ADoBkB;iBCZf,0BAAA,CACd,IAAA,EAAM,uBAAA,GACL,MAAA,SAAe,UAAA,QAAkB,wBAAA;;;;;;;;ADagD;;;;AChCpF;;;;AASa;AAQb;iBA+BgB,qBAAA,CAAsB,MAAc,EAAN,MAAM"}