@commonlyai/cli 0.1.157 → 0.1.159

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/README.md CHANGED
@@ -27,3 +27,17 @@ node --experimental-vm-modules node_modules/.bin/jest --no-coverage
27
27
  Instance-selection tests use distinct persisted `savedAt` values and both insertion orders.
28
28
  Keep active-instance precedence separate from the newest-match fallback; back-to-back
29
29
  `saveInstance` calls can share a millisecond and hide a broken selection branch.
30
+
31
+ ### Keep hosted memory when connecting a local agent
32
+
33
+ A hosted agent's local handoff card includes `--memory-from <hosted-agent>` and
34
+ `--memory-instance <hosted-instance>` on the attach command. After login, attach
35
+ copies that source's long-term memory into the local identity before returning
36
+ its runnable configuration. Both identities must be accessible through the
37
+ logged-in account's owner memory API. No hosted runtime credential is moved.
38
+
39
+ This is a snapshot, not a shared identity or continuing synchronization. Attach
40
+ refuses to replace different existing local memory or copy into a non-private
41
+ long-term section. A failed copy stops attach; correct the error and retry before
42
+ running the local agent. A retry resumes only your matching active local installation,
43
+ without changing its configuration or scopes. Repeating a copy with identical memory is safe.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.157",
3
+ "version": "0.1.159",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -18,6 +18,7 @@ import { fileURLToPath } from 'url';
18
18
  import { createHash } from 'crypto';
19
19
 
20
20
  import { createClient } from '../lib/api.js';
21
+ import { copyHandoffMemory } from '../lib/handoff-memory.js';
21
22
  import {
22
23
  buildSpawnId,
23
24
  createSpawnCredentialLease,
@@ -819,6 +820,8 @@ export const performAttach = async ({
819
820
  displayName,
820
821
  envPath = null,
821
822
  wakeOnMessage = false,
823
+ memoryFrom = null,
824
+ memoryInstance = 'default',
822
825
  log = () => {},
823
826
  adapterRegistry = { getAdapter, listAdapterNames },
824
827
  }) => {
@@ -953,6 +956,7 @@ export const performAttach = async ({
953
956
  // on config.environment so cross-driver implementations can realize it
954
957
  // server-side without re-reading the user's file.
955
958
  const installResult = await client.post('/api/registry/install', {
959
+ ...(memoryFrom ? { resumeExisting: true } : {}),
956
960
  agentName,
957
961
  podId,
958
962
  displayName: displayName || agentName,
@@ -975,6 +979,16 @@ export const performAttach = async ({
975
979
  const installation = installResult.installation || installResult;
976
980
  const instanceId = installation.instanceId || 'default';
977
981
 
982
+ if (memoryFrom) {
983
+ const memoryCopy = await copyHandoffMemory(client, {
984
+ sourceAgentName: memoryFrom, sourceInstanceId: memoryInstance,
985
+ targetAgentName: installation.agentName, targetInstanceId: instanceId,
986
+ });
987
+ log(memoryCopy.reason === 'source-empty'
988
+ ? 'hosted agent has no long-term memory to copy'
989
+ : 'hosted long-term memory is present in the local agent');
990
+ }
991
+
978
992
  let runtimeToken = installResult.runtimeToken;
979
993
  if (!runtimeToken) {
980
994
  // ADR-005 §detach + reattach: the agent User row's hashed token persists
@@ -993,6 +1007,8 @@ export const performAttach = async ({
993
1007
  throw new Error('Runtime token was not returned by install or tokens endpoint');
994
1008
  }
995
1009
 
1010
+
1011
+
996
1012
  return {
997
1013
  installation,
998
1014
  instanceId,
@@ -3104,6 +3120,8 @@ Docs:
3104
3120
  .description('Wrap a local CLI as a Commonly agent (stub|claude|codex|opencode|qwen|dsh|…)')
3105
3121
  .requiredOption('--pod <podId>', 'Pod ID to install into')
3106
3122
  .requiredOption('--name <name>', 'Agent name (e.g. my-claude)')
3123
+ .option('--memory-from <agent>', 'Copy long-term memory from a hosted agent you own')
3124
+ .option('--memory-instance <id>', 'Hosted source instance for --memory-from', 'default')
3107
3125
  .option('--display <name>', 'Display name shown in the pod')
3108
3126
  .option('--env <path>', 'Path to environment.json (ADR-008 — sandbox/skills/MCP)')
3109
3127
  .option('--import-memory [path]', 'Import local memory (CLAUDE.md / MEMORY.md / ~/.claude project memory, or a given file/dir) into the agent after attach')
@@ -3130,6 +3148,8 @@ Docs:
3130
3148
  displayName: opts.display,
3131
3149
  envPath: envAbsPath,
3132
3150
  wakeOnMessage: Boolean(opts.wakeOnMessage),
3151
+ memoryFrom: opts.memoryFrom,
3152
+ memoryInstance: opts.memoryInstance,
3133
3153
  log: (line) => console.warn(`[attach] ${line}`),
3134
3154
  });
3135
3155
 
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Keep the provider key available to pi's per-call auth resolver, but out of
3
+ * shells started by its model bash tool and by manual ! / !! commands.
4
+ * This limits environment inheritance; pi itself is not an OS sandbox.
5
+ */
6
+ import { createBashTool, createLocalBashOperations } from '@earendil-works/pi-coding-agent';
7
+
8
+ export default function commonlyShellEnvironment(pi) {
9
+ const providerKey = process.env.COMMONLY_PI_PROVIDER_KEY_ENV;
10
+ if (!providerKey) throw new Error('pi adapter: missing provider key environment name');
11
+ const excluded = new Set([
12
+ providerKey, 'COMMONLY_LITELLM_KEY', 'COMMONLY_PI_PROVIDER_KEY_ENV',
13
+ ].map((key) => key.toUpperCase()));
14
+ const cleanEnv = (env) => {
15
+ const clean = { ...env };
16
+ // Windows environment lookup ignores case; spreading it loses that behavior.
17
+ for (const key of Object.keys(clean)) {
18
+ if (excluded.has(key.toUpperCase())) delete clean[key];
19
+ }
20
+ return clean;
21
+ };
22
+ const spawnHook = (context) => ({ ...context, env: cleanEnv(context.env) });
23
+ const bash = createBashTool(process.cwd(), { spawnHook });
24
+ pi.registerTool({
25
+ ...bash,
26
+ execute(id, params, signal, onUpdate, ctx) {
27
+ return createBashTool(ctx.cwd, { spawnHook }).execute(id, params, signal, onUpdate, ctx);
28
+ },
29
+ });
30
+ const local = createLocalBashOperations();
31
+ pi.on('user_bash', () => ({
32
+ operations: {
33
+ exec(command, cwd, options) {
34
+ return local.exec(command, cwd, {
35
+ ...options,
36
+ env: cleanEnv(options.env ?? process.env),
37
+ });
38
+ },
39
+ },
40
+ }));
41
+ }
@@ -72,6 +72,7 @@ const THINKING = { none: 'off', off: 'off', minimal: 'minimal', low: 'low', medi
72
72
  export const thinkingFor = (effort) => (effort ? THINKING[String(effort).toLowerCase()] || null : null);
73
73
 
74
74
  const BRIDGE_PATH = join(dirname(fileURLToPath(import.meta.url)), 'pi-commonly-mcp.mjs');
75
+ const SHELL_ENV_PATH = join(dirname(fileURLToPath(import.meta.url)), 'pi-shell-env.mjs');
75
76
 
76
77
  // Same substitution contract as claude.js / codex.js: ${COMMONLY_*}
77
78
  // placeholders in the declared MCP env are the wrapper's per-(agent, pod)
@@ -457,6 +458,9 @@ export default {
457
458
  ...baseEnv,
458
459
  PI_CODING_AGENT_DIR: agentDir,
459
460
  PI_SKIP_VERSION_CHECK: '1',
461
+ // A variable NAME, never its value. The always-loaded extension uses
462
+ // this to scrub custom provider keys as well as the default LiteLLM key.
463
+ COMMONLY_PI_PROVIDER_KEY_ENV: provider.apiKeyEnv,
460
464
  };
461
465
  // `baseEnv` is normally the process environment, which carries the
462
466
  // bootstrap export. Nothing below this process needs the value: the bridge
@@ -472,6 +476,8 @@ export default {
472
476
  prompt: fullPrompt, provider: provider.name, model, thinking, sessionId, isResume, sessionDir,
473
477
  bridge: servers.length ? (ctx._bridgePath || BRIDGE_PATH) : null,
474
478
  });
479
+ // Shell isolation must not depend on whether this turn declares MCP.
480
+ args.splice(args.length - 1, 0, '-e', SHELL_ENV_PATH);
475
481
 
476
482
  const reply = await runPi({
477
483
  args,
@@ -0,0 +1,23 @@
1
+ /** Copy only long-term memory using the logged-in owner's revision-checked API. */
2
+ export const copyHandoffMemory = async (client, {
3
+ sourceAgentName, sourceInstanceId = 'default', targetAgentName, targetInstanceId = 'default',
4
+ }) => {
5
+ const endpoint = (name, instance) => `/api/agent-memory/${encodeURIComponent(name)}/${encodeURIComponent(instance)}/editable`;
6
+ const source = await client.get(endpoint(sourceAgentName, sourceInstanceId));
7
+ const content = source?.sections?.long_term?.content;
8
+ if (typeof content !== 'string') throw new Error('Hosted memory response is missing long_term content');
9
+ if (!content) return { copied: false, reason: 'source-empty' };
10
+ const targetPath = endpoint(targetAgentName, targetInstanceId);
11
+ const target = await client.get(targetPath);
12
+ const prior = target?.sections?.long_term;
13
+ if (typeof prior?.content !== 'string') throw new Error('Local memory response is missing long_term content');
14
+ if (prior.visibility !== 'private') throw new Error('Local long-term memory must be private before copying hosted memory');
15
+ if (prior.content === content) return { copied: false, reason: 'already-copied' };
16
+ if (prior.content) throw new Error('Local agent already has different memory; choose a new local name');
17
+ // A concurrent first write wins rather than being overwritten by this copy.
18
+ await client.patch(`${targetPath}/long_term`, {
19
+ copyFrom: { agentName: sourceAgentName, instanceId: sourceInstanceId },
20
+ expectedUpdatedAt: prior.updatedAt ?? null,
21
+ });
22
+ return { copied: true };
23
+ };