@kaiba-cloud/orbital-harness-pi 0.0.0-stage → 0.0.2

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.
package/dist/plugin.js ADDED
@@ -0,0 +1,31 @@
1
+ import { createRequire as __orbitalCreateRequire } from 'node:module';
2
+ const require = __orbitalCreateRequire(import.meta.url);
3
+ import {
4
+ servePlugin
5
+ } from "./chunks/chunk-MOWIDULI.js";
6
+
7
+ // src/plugin.ts
8
+ import { fileURLToPath } from "node:url";
9
+ var NAME = "orbital-harness-pi";
10
+ var HARNESS = "pi";
11
+ var FOLDER = { folder: ".pi", instructions: "AGENTS.md", agents: "agents", skills: "skills" };
12
+ function install(request) {
13
+ return { written: [], notes: [`${HARNESS} runs in the turns of an orbital node, and reaches the orbital tools over MCP in each turn: agents in ${FOLDER.folder}/${FOLDER.agents} run on it`] };
14
+ }
15
+ function plugin() {
16
+ return {
17
+ name: NAME,
18
+ version: "0.0.1",
19
+ permissions: { network: [], secrets: [], models: [] },
20
+ ports: {
21
+ harnesses: {
22
+ harnesses: [{ id: HARNESS, description: "The Pi coding agent: the model API of the agent, with read, bash, edit and write, and the orbital tools.", callsModel: true, browser: false, folder: FOLDER }],
23
+ command: async () => ({ command: [process.execPath, fileURLToPath(new URL("turn.js", import.meta.url))], egress: [] }),
24
+ install: async (request) => install(request)
25
+ }
26
+ }
27
+ };
28
+ }
29
+
30
+ // src/main.ts
31
+ servePlugin(() => plugin());
package/dist/turn.js ADDED
@@ -0,0 +1,155 @@
1
+ import { createRequire as __orbitalCreateRequire } from 'node:module';
2
+ const require = __orbitalCreateRequire(import.meta.url);
3
+ import {
4
+ textPart,
5
+ thinkingPart,
6
+ toolCallPart,
7
+ toolResultPart
8
+ } from "./chunks/chunk-MOWIDULI.js";
9
+
10
+ // src/turn.ts
11
+ import { randomUUID } from "node:crypto";
12
+ import { mkdirSync, readFileSync, readdirSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { Type } from "@mariozechner/pi-ai";
15
+ import { AuthStorage, DefaultResourceLoader, ModelRegistry, SessionManager, SettingsManager, createAgentSession, defineTool } from "@mariozechner/pi-coding-agent";
16
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
17
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
18
+ import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici";
19
+
20
+ // src/lines.ts
21
+ function assistantParts(message) {
22
+ return message.content.flatMap((content) => {
23
+ if (content.type === "text" && content.text) return [textPart(content.text)];
24
+ if (content.type === "thinking" && content.thinking && !content.redacted) return [thinkingPart(content.thinking)];
25
+ if (content.type === "toolCall" && content.id && content.name) return [toolCallPart({ id: content.id, name: content.name, input: content.arguments ?? {} })];
26
+ return [];
27
+ });
28
+ }
29
+ function resultText(result) {
30
+ if (typeof result === "string") return result;
31
+ const content = result?.content;
32
+ if (Array.isArray(content)) return content.flatMap((part) => part.type === "text" && part.text ? [part.text] : part.type === "image" ? ["[image]"] : []).join("\n");
33
+ return JSON.stringify(result ?? null);
34
+ }
35
+ function toolResult(callId, name, result, isError) {
36
+ return toolResultPart({ callId, name, text: resultText(result), isError });
37
+ }
38
+ function answerOf(message) {
39
+ return message.content.flatMap((content) => content.type === "text" && content.text ? [content.text] : []).join("\n");
40
+ }
41
+ var UsageTotals = class {
42
+ byModel = /* @__PURE__ */ new Map();
43
+ add(message) {
44
+ const key = `${message.provider}:${message.model}`;
45
+ const total = this.byModel.get(key) ?? { provider: message.provider, model: message.model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, costUsd: 0, llmCalls: 0 };
46
+ total.inputTokens += message.usage.input;
47
+ total.outputTokens += message.usage.output;
48
+ total.cacheReadTokens += message.usage.cacheRead;
49
+ total.cacheWriteTokens += message.usage.cacheWrite;
50
+ total.costUsd += message.usage.cost.total;
51
+ total.llmCalls += 1;
52
+ this.byModel.set(key, total);
53
+ }
54
+ line() {
55
+ return this.byModel.size === 0 ? null : { type: "usage", models: [...this.byModel.values()] };
56
+ }
57
+ };
58
+
59
+ // src/turn.ts
60
+ var line = (value) => process.stdout.write(`${JSON.stringify(value)}
61
+ `);
62
+ var say = (role, parts) => {
63
+ if (parts.length > 0) line({ type: "message", message: { messageId: randomUUID(), role, parts } });
64
+ };
65
+ function fail(message) {
66
+ line({ type: "error", message });
67
+ process.exit(1);
68
+ }
69
+ async function orbitalTools(spec) {
70
+ const [command, ...args] = spec.tools.command;
71
+ if (!command) return { tools: [], close: async () => void 0 };
72
+ const client = new Client({ name: "orbital-harness-pi", version: "0.0.1" });
73
+ const env = Object.fromEntries(Object.entries({ ...process.env, ...spec.tools.env }).filter((entry) => typeof entry[1] === "string"));
74
+ await client.connect(new StdioClientTransport({ command, args, env, stderr: "ignore" }));
75
+ const { tools } = await client.listTools();
76
+ return {
77
+ tools: tools.map((tool) => defineTool({
78
+ name: tool.name,
79
+ label: tool.title ?? tool.name,
80
+ description: tool.description ?? tool.name,
81
+ parameters: Type.Unsafe(tool.inputSchema),
82
+ execute: async (_id, params) => {
83
+ const result = await client.callTool({ name: tool.name, arguments: params });
84
+ const text = resultText(result);
85
+ if (result.isError === true) throw new Error(text);
86
+ return { content: [{ type: "text", text }], details: {} };
87
+ }
88
+ })),
89
+ close: () => client.close()
90
+ };
91
+ }
92
+ async function main() {
93
+ setGlobalDispatcher(new EnvHttpProxyAgent({ bodyTimeout: 0, headersTimeout: 0 }));
94
+ const file = process.env.ORBITAL_HARNESS_TURN;
95
+ if (!file) fail("ORBITAL_HARNESS_TURN names no turn spec.");
96
+ const spec = JSON.parse(readFileSync(file, "utf8"));
97
+ if (!spec.model || !spec.model.includes(":")) fail(`An agent on ${spec.harness} names its model as <provider>:<model>, such as anthropic:claude-sonnet-5-5, with model: in its agent file.`);
98
+ const provider = spec.model.slice(0, spec.model.indexOf(":"));
99
+ const modelId = spec.model.slice(spec.model.indexOf(":") + 1);
100
+ const key = spec.credentials.find((credential) => credential.provider === provider)?.payload;
101
+ if (!key) fail(`The turn has no ${provider} key. Store one with: orbital providers set ${provider}`);
102
+ const authStorage = AuthStorage.inMemory();
103
+ authStorage.setRuntimeApiKey(provider, key);
104
+ const modelRegistry = ModelRegistry.inMemory(authStorage);
105
+ const model = modelRegistry.find(provider, modelId);
106
+ if (!model) fail(`Pi knows no model ${provider}:${modelId}.`);
107
+ const piDir = join(spec.sessionDir, "pi");
108
+ mkdirSync(piDir, { recursive: true });
109
+ const loader = new DefaultResourceLoader({ cwd: spec.workspaceDir, agentDir: join(piDir, "agent"), systemPrompt: spec.systemPrompt, noSkills: true });
110
+ await loader.reload();
111
+ const resumes = spec.resume && readdirSync(piDir).some((name) => name.endsWith(".jsonl"));
112
+ const sessionManager = resumes ? SessionManager.continueRecent(spec.workspaceDir, piDir) : SessionManager.create(spec.workspaceDir, piDir);
113
+ const orbital = await orbitalTools(spec);
114
+ const { session } = await createAgentSession({
115
+ cwd: spec.workspaceDir,
116
+ agentDir: join(piDir, "agent"),
117
+ authStorage,
118
+ modelRegistry,
119
+ model,
120
+ resourceLoader: loader,
121
+ sessionManager,
122
+ settingsManager: SettingsManager.inMemory({ retry: { enabled: false } }),
123
+ customTools: orbital.tools
124
+ });
125
+ await session.bindExtensions({});
126
+ const usage = new UsageTotals();
127
+ let last = null;
128
+ session.subscribe((event) => {
129
+ if (event.type === "message_end" && event.message.role === "assistant") {
130
+ const message = event.message;
131
+ last = message;
132
+ usage.add(message);
133
+ say("ROLE_AGENT", assistantParts(message));
134
+ }
135
+ if (event.type === "tool_execution_end") say("ROLE_USER", [toolResult(event.toolCallId, event.toolName, event.result, event.isError)]);
136
+ });
137
+ const stop = () => {
138
+ void session.abort().finally(() => process.exit(143));
139
+ };
140
+ process.once("SIGTERM", stop);
141
+ process.once("SIGINT", stop);
142
+ try {
143
+ await session.prompt(spec.prompt);
144
+ } finally {
145
+ await orbital.close().catch(() => void 0);
146
+ }
147
+ const totals = usage.line();
148
+ if (totals) line(totals);
149
+ const ended = last;
150
+ if (!ended) fail("Pi answered nothing.");
151
+ if (ended.stopReason === "error" || ended.stopReason === "aborted") fail(ended.errorMessage ?? `Pi stopped: ${ended.stopReason}.`);
152
+ line({ type: "result", text: answerOf(ended) });
153
+ process.exit(0);
154
+ }
155
+ main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "orbital-harness-pi",
3
+ "command": ["node", "dist/plugin.js"],
4
+ "harnesses": [{ "id": "pi", "folder": ".pi", "instructions": "AGENTS.md", "agents": "agents", "skills": "skills" }]
5
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@kaiba-cloud/orbital-harness-pi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "The adapter of the harness pi for orbital: its folder .pi, its install, and a turn program on the Pi coding agent",
4
+ "version": "0.0.2",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.18"
9
+ },
10
+ "scripts": {
11
+ "build": "node scripts/build.mjs",
12
+ "check-types": "tsc -p tsconfig.json",
13
+ "test": "vitest run"
14
+ },
15
+ "dependencies": {
16
+ "@mariozechner/pi-ai": "0.73.1",
17
+ "@mariozechner/pi-coding-agent": "0.73.1",
18
+ "@modelcontextprotocol/sdk": "^1.31.0",
19
+ "undici": "^7.19.1"
20
+ },
21
+ "devDependencies": {
22
+ "@kaiba-cloud/orbital-sdk": "workspace:*",
23
+ "esbuild": "^0.25.0",
24
+ "typescript": "~5.9.3"
25
+ },
26
+ "files": [
27
+ "orbital-plugin.json",
28
+ "dist"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ }
33
+ }