@north-light/cli 0.3.674 → 0.3.675
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/clients/attach/session/connection.d.ts +2 -1
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/viewer.d.ts +11 -1
- package/dist/clients/attach/viewer.js +524 -524
- package/dist/commands/person-settings.d.ts +5 -0
- package/dist/commands/person-settings.js +1 -1
- package/dist/core/graph/reader.d.ts +2 -1
- package/dist/core/graph/reader.js +3 -3
- package/dist/core/graph/repo-sync/repos.d.ts +24 -3
- package/dist/core/graph/repo-sync/repos.js +4 -4
- package/dist/core/profiles/select.d.ts +3 -1
- package/dist/core/profiles/select.js +25 -25
- package/dist/core/runtime/bearings.d.ts +3 -3
- package/dist/core/runtime/bearings.js +6 -6
- package/dist/core/runtime/boot-root.d.ts +3 -3
- package/dist/core/runtime/boot-root.js +6 -4
- package/dist/core/runtime/deliver-live.js +1 -1
- package/dist/core/runtime/front-door.js +1 -1
- package/dist/core/runtime/starting-screen.d.ts +12 -0
- package/dist/core/runtime/starting-screen.js +9 -0
- package/dist/core/substrate/delivery/deliver.d.ts +1 -1
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/subject.d.ts +3 -1
- package/dist/core/substrate/subject.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/delivery.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +3 -2
- package/packages/crouter-api/dist/clients/attach/viewer.js +16 -7
- package/packages/crouter-api/dist/commands/person-settings.js +10 -3
- package/packages/crouter-api/dist/core/graph/reader.js +9 -4
- package/packages/crouter-api/dist/core/graph/repo-sync/repos.js +56 -13
- package/packages/crouter-api/dist/core/profiles/select.js +17 -7
- package/packages/crouter-api/dist/core/runtime/bearings.js +11 -12
- package/packages/crouter-api/dist/core/runtime/deliver-live.js +1 -1
- package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +3 -3
- package/packages/crouter-api/dist/core/substrate/subject.js +4 -4
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +6 -4
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1 +1,6 @@
|
|
|
1
|
+
import type { PersonSettingsDTO } from '../api/index.js';
|
|
2
|
+
/** This process's live settings (every write it has made included), for handing to a viewer bundle that holds its own cache. */
|
|
3
|
+
export declare function loadedPersonSettings(): PersonSettingsDTO;
|
|
1
4
|
export declare function loadPersonSettingsViaApi(): Promise<void>;
|
|
5
|
+
/** Install a settings answer already in hand (no request) and wire this process's reload and write transports. */
|
|
6
|
+
export declare function installPersonSettingsDto(loaded: PersonSettingsDTO): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var
|
|
1
|
+
var a=Object.defineProperty;var n=(t,e)=>a(t,"name",{value:e,configurable:!0});import{ApiError as p}from"../api/index.js";import{personId as c,setPersonId as f}from"../core/canvas/person-state.js";import{currentSnapshot as g,installPersonSnapshot as S,setSettingsReloader as m,setSettingsTransport as l,SettingsRevisionConflictError as u}from"../core/scoped-state/person-store.js";import{cliClient as r}from"./api-client.js";const s=n(t=>t.snapshot,"fromDto");function A(){return{person:c(),snapshot:g()}}n(A,"loadedPersonSettings");async function C(){h(await r().getSettings())}n(C,"loadPersonSettingsViaApi");function h(t){f(t.person),S(t.person,s(t)),m(async()=>s(await r().getSettings())),l(async(e,i)=>{try{return s(await r().putSettings({ops:i}))}catch(o){throw o instanceof p&&o.status===409?new u:o}})}n(h,"installPersonSettingsDto");export{h as installPersonSettingsDto,C as loadPersonSettingsViaApi,A as loadedPersonSettings};
|
|
@@ -2,9 +2,10 @@ import type { RequestPrincipal } from '../../daemon/api/router.js';
|
|
|
2
2
|
import { type ActiveGrant } from '../grants/mirror.js';
|
|
3
3
|
import { type CanvasDb } from '../canvas/db.js';
|
|
4
4
|
import type { Checkout, ObjectRow, Reader } from './types.js';
|
|
5
|
+
import { type ReadAccess } from './repo-sync/repos.js';
|
|
5
6
|
import type { ProfileProject } from '../../api/dto/profiles.js';
|
|
6
7
|
/** The repos enclosing a directory, with their checkout roots, nearest first. `person` is whose read permission filters them (default: the request's person). */
|
|
7
|
-
export type ReposFn = (cwd: string, person?: string) => Promise<Checkout[]>;
|
|
8
|
+
export type ReposFn = (cwd: string, person?: string, access?: ReadAccess) => Promise<Checkout[]>;
|
|
8
9
|
/** A node's view of repos: for the checkouts enclosing its cwd, every repo object of their remotes the person may read (own first, then oldest), then
|
|
9
10
|
* the repos its profile names (an entry's `repo`, and the checkouts of its `path`), in manifest order, each repo once. A repo entry needs no folder or
|
|
10
11
|
* git; one the person may not read adds nothing. A project path that no longer exists, is not in a repo, or has no work tree contributes nothing. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!
|
|
3
|
-
WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,
|
|
1
|
+
var $=Object.defineProperty;var s=(o,e)=>$(o,"name",{value:e,configurable:!0});import{coveredByAny as j,isSandboxedNode as H}from"../../shared/env.js";import{projectPaths as W}from"../../api/dto/profiles.js";import{existsSync as S}from"node:fs";import{CrtrError as D}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as F}from"@north-light/identity";import{activeGrant as C,grantFor as b,runtimeScope as B}from"../grants/mirror.js";import{withCanvasWrite as J}from"../canvas/db.js";import{ApiError as P}from"../../api/errors.js";import{pluginAppToken as k}from"../secrets.js";import{loadExactProfileManifest as G}from"../profiles/manifest.js";import{ensureOwner as x,getById as q,nodeObject as U,ownerForGrantee as Y,profileHandle as z}from"./objects.js";import{personId as K,personIdAsync as A}from"../canvas/person.js";import{OBJECT_TYPE as Q}from"../permissions/builtin.js";import{warmCheckoutDirs as L}from"../checkout-identities.js";import{fillProfileProjectRepo as V}from"../profiles/manifest.js";import{emitEvent as X}from"../events/emit.js";import{isCloudRole as _}from"../canvas/person-state.js";import{loadReadAccess as Z,mayRead as I,prefetchRepoReads as ee,reposForCwd as oe,warmCheckoutIdentities as O}from"./repo-sync/repos.js";async function M(o,e,t,r,n,a){const u=t===null?[]:n.projects(t),c=u.length===0?void 0:a??await A(),p=c===void 0?void 0:await Z(o,c);p!==void 0&&c!==void 0&&await ee(o,c,[e,...u.flatMap(i=>i.path!==void 0&&(_()||S(i.path))?[i.path]:[])],p);const f=await r(e,a,p),d=new Set(f.map(i=>i.repo.id)),m=[],E=[];for(const i of u){if(i.repo!==void 0&&!d.has(i.repo)){const l=await n.object(i.repo);l!==null&&l.type==="repo"&&l.deleted_at===null&&await I(o,c??a??await A(),l.id,p)&&(d.add(l.id),m.push(l))}if(i.path===void 0||!_()&&!S(i.path))continue;let w;try{w=await r(i.path,a,p)}catch(l){if(l instanceof D&&l.code==="git-lookup-failed")continue;throw l}for(const l of w)d.has(l.repo.id)||(d.add(l.repo.id),m.push(l.repo),E.push(l))}return{repos:f.map(i=>i.repo),checkouts:f,projectRepos:m,projectCheckouts:E}}s(M,"viewRepos");async function Fe(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?W(h(o).projects(t.profile_id)):[];if(_()){await te(t.profile_id,[t.cwd,...r]);return}await O(t.cwd);for(const n of r)S(n)&&await O(n)}s(Fe,"warmNodeRepos");async function te(o,e){if(await L(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await J(async n=>await oe(n,t.path)))[0];r!==void 0&&await V(o,t.path,r.id)}catch(r){X({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(te,"warmCloudNodeCheckouts");async function Ce(o,e,t){if(!_()){for(const n of t)await O(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await L(r?.profile_id,t)}s(Ce,"warmNodeDirs");async function be(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await N(o)};if(e.class==="app")return{class:"app",app:await R(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await N(o)};const c=await b(e.actor.app,e.sub);if(!c)throw new P(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const p=e.actor.node_scopes;return{class:"app",app:await R(o,e.actor.app),place:e.actor.place,launched:p,scopes:p===null?c.resolved:p.filter(f=>j(c.resolved,f))}}if(e.class==="cron"){const c=e.grant?(await C(e.grant))?.resolved??[]:[],p=e.scopes;return{class:"app",app:await R(o,e.app),scopes:p===null?c:p.filter(f=>j(c,f)),launched:p,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=h(o),n=await U(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),u=a.app===null?null:await r.object(a.app);if(!u)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:u,scopes:await T(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await M(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,u)}}s(be,"readerFor");async function ne(o,e,t,r=h(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),u=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
|
|
2
|
+
sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!u)throw new Error(`no node ${e}`);const{grantee:c,sub:p,grant_id:f,scopes_json:d,cwd:m,profile_id:E,app:i}=u,w=i===null?null:await r.object(i);if(!w)throw new Error(`node ${e} has no app`);const l=d===null?null:JSON.parse(d);return{class:"node",node:a,app:w,scopes:await T(c,p??"",f,l,r,n),launched:l,cwd:m,...await M(o,m,E,t,r,p||void 0),profile:E===null?null:await r.profile(E,w)}}s(ne,"readerForNode");class re extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function xe(o,e,t=async()=>[],r=h(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await ae(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ne(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const c=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!c)throw new re;const p=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(c.id))?.external_id??"app:terminal",f=B(),d=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(p,...f.args),m=s(g=>JSON.parse(g.resolved_scopes_json).filter(y=>y.mode==="always").map(y=>F(y.scope)),"always"),E=d.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(Q,e.id)).map(g=>g.subject_id)):null,i=E===null?void 0:d.find(g=>E.has(g.sub.replace(/^user:/,"")))?.sub,w=i===void 0?null:await r.grantFor(p,i),l=a.type==="person"?null:d.length===0?r.pluginScopes(p):d.length===1?m(d[0]):w?.resolved??null;return{class:"object",object:e,node:e,owner:a,app:c,scopes:l,...w===null?{}:{sub:w.sub},repos:a.type==="repo"?[a]:[]}}s(xe,"readerForObject");async function Ae(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>F(a.scope))}s(Ae,"appScopesNow");async function ae(o,e,t,r){const n=await N(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await R(o,t.app),u=t?.app==null?null:await r.grantFor(t.app,t.sub),c=t===null||u===null?null:t.node_scopes===null?u.resolved:t.node_scopes.filter(f=>j(u.resolved,f)),p=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:p,app:p,scopes:c,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(ae,"readerForStub");function h(o){return{grantById:C,grantFor:b,pluginScopes:s(e=>k(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await q(o,e),"object"),profile:s(async(e,t)=>await se(o,e,t),"profile"),projects:s(e=>H()?[]:v(e)?.manifest.projects??[],"projects")}}s(h,"liveLookups");function Le(o){const e=h(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Le,"publishLookups");async function T(o,e,t,r,n,a=!1){const u=t?await n.grantById(t):await n.grantFor(o,e),c=u&&u.grantee===o?u.resolved:null;if(c===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?c:r.filter(p=>j(c,p))}s(T,"nodeScopes");async function N(o){return await Y(o,K())}s(N,"personObject");async function R(o,e){return await x(o,"app","app",e,e.replace(/^app:/,""))}s(R,"appObject");async function se(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
|
|
3
|
+
WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,z(e,G(e).manifest.name),t)}s(se,"profileObject");export{re as NoOwningAppError,Ae as appScopesNow,h as liveLookups,se as profileObject,Le as publishLookups,be as readerFor,ne as readerForNode,xe as readerForObject,M as viewRepos,te as warmCloudNodeCheckouts,Ce as warmNodeDirs,Fe as warmNodeRepos};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Checkout, ObjectRow } from '../types.js';
|
|
2
2
|
import { handleHint } from './identity.js';
|
|
3
3
|
import type { CanvasDb } from '../../canvas/db.js';
|
|
4
|
+
import { subjectSet } from '../../permissions/evaluator.js';
|
|
5
|
+
import { loadDefinitions } from '../../permissions/schemas.js';
|
|
4
6
|
export { handleHint };
|
|
5
7
|
export interface RepoIdentity {
|
|
6
8
|
scheme: 'git' | 'local-path';
|
|
@@ -10,14 +12,33 @@ export interface RepoIdentity {
|
|
|
10
12
|
/** The repo object of the person this request runs as for an identity, created on first sight. A handle already
|
|
11
13
|
* held by another repo gets `-2`, `-3`, … appended. */
|
|
12
14
|
export declare function ensureRepo(db: CanvasDb, id: RepoIdentity, handle?: string): Promise<ObjectRow>;
|
|
15
|
+
/** What a permission check on repos needs from the database: the schema definitions and the person's subject set. A caller checking many
|
|
16
|
+
* repos for one person in one request loads it once and passes it down. */
|
|
17
|
+
export interface ReadAccess {
|
|
18
|
+
defs: Awaited<ReturnType<typeof loadDefinitions>>;
|
|
19
|
+
subjects: Awaited<ReturnType<typeof subjectSet>>;
|
|
20
|
+
/** Filled by `prefetchRepoReads`: the answer of `readableRepos` per `scheme\0externalId`, and every local-path repo identity. */
|
|
21
|
+
readable?: Map<string, {
|
|
22
|
+
readable: ObjectRow[];
|
|
23
|
+
heldByPerson: boolean;
|
|
24
|
+
}>;
|
|
25
|
+
localPaths?: Array<ObjectRow & {
|
|
26
|
+
path: string;
|
|
27
|
+
person: string;
|
|
28
|
+
}>;
|
|
29
|
+
}
|
|
30
|
+
export declare function loadReadAccess(db: CanvasDb, person: string): Promise<ReadAccess>;
|
|
13
31
|
/** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
|
|
14
|
-
export declare function mayRead(db: CanvasDb, person: string, id: string): Promise<boolean>;
|
|
32
|
+
export declare function mayRead(db: CanvasDb, person: string, id: string, access?: ReadAccess): Promise<boolean>;
|
|
15
33
|
/** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
|
|
16
34
|
* then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
|
|
17
|
-
export declare function readableRepos(db: CanvasDb, person: string, scheme: string, externalId: string): Promise<{
|
|
35
|
+
export declare function readableRepos(db: CanvasDb, person: string, scheme: string, externalId: string, access?: ReadAccess): Promise<{
|
|
18
36
|
readable: ObjectRow[];
|
|
19
37
|
heldByPerson: boolean;
|
|
20
38
|
}>;
|
|
39
|
+
/** For a request that resolves many directories for one person: read once what each `checkoutsForCwd` would read per directory (the readable
|
|
40
|
+
* repos of every git identity in `dirs`, and the local-path repos) and store it on `access`. */
|
|
41
|
+
export declare function prefetchRepoReads(db: CanvasDb, person: string, dirs: readonly string[], access: ReadAccess): Promise<void>;
|
|
21
42
|
/** Repos enclosing `cwd`, nearest first: every enclosing git checkout (created
|
|
22
43
|
* on first sight) and every existing local-path repo whose path is `cwd` or
|
|
23
44
|
* an ancestor of it. A non-git folder is never created here. */
|
|
@@ -28,4 +49,4 @@ export declare function warmCheckoutIdentities(cwd: string): Promise<void>;
|
|
|
28
49
|
/** `reposForCwd` with the directory each repo is checked out at. Each git checkout yields every repo object of its remote that `person` (default: the
|
|
29
50
|
* request's person) may read: their own first, then the others oldest first. A personal repo object is created only when the person holds none for the
|
|
30
51
|
* remote; one they hold but may no longer read (a group they left) contributes nothing. */
|
|
31
|
-
export declare function checkoutsForCwd(db: CanvasDb, cwd: string, person?: string): Promise<Checkout[]>;
|
|
52
|
+
export declare function checkoutsForCwd(db: CanvasDb, cwd: string, person?: string, access?: ReadAccess): Promise<Checkout[]>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(
|
|
3
|
-
WHERE o.type = 'repo' AND o.deleted_at IS NULL AND i.scheme
|
|
4
|
-
WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all()).
|
|
1
|
+
var $=Object.defineProperty;var p=(e,o)=>$(e,"name",{value:o,configurable:!0});import{resolve as E,sep as N}from"node:path";import{CrtrError as R}from"../../errors.js";import{realpathOrSelf as y}from"../../fs-utils.js";import{ExitCode as O}from"../../../types.js";import{personIdAsync as x}from"../../canvas/person.js";import{ensureOwner as L}from"../objects.js";import{checkoutChain as j,handleHint as D}from"./identity.js";import{checkoutChainOf as S}from"../../checkout-identities.js";import{subjectSet as P}from"../../permissions/evaluator.js";import{loadDefinitions as T}from"../../permissions/schemas.js";import{compilePermission as A}from"../../permissions/compile.js";import{f as F,raw as b}from"../../permissions/sql.js";import{OBJECT_TYPE as k}from"../../permissions/builtin.js";async function M(e,o,r,n){return await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
|
|
2
|
+
WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(o,r,n)??null}p(M,"existingRepo");async function H(e,o,r){const n=await M(e,await x(),o.scheme,o.externalId);if(n)return n;const i=r??o.handleHint;await e.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`repo-handle:${i}`);const c=e.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let a=i;for(let s=2;await c.get(a);s++)a=`${i}-${s}`;return await L(e,"repo",o.scheme,o.externalId,a)}p(H,"ensureRepo");async function _(e,o){return{defs:await T(e),subjects:await P(e,o.replace(/^user:/,""))}}p(_,"loadReadAccess");async function ae(e,o,r,n){const{defs:i,subjects:c}=n??await _(e,o),a=A(i,c,k,"read",F`${r}::text`);return(await e.prepareUncached(`SELECT ${a.sql} AS ok`).get(...a.params))?.ok===!0}p(ae,"mayRead");async function W(e,o,r,n,i){const c=`${r}\0${n}`,a=i?.readable?.get(c);return a!==void 0?{readable:[...a.readable],heldByPerson:a.heldByPerson}:(await g(e,o,[{scheme:r,externalId:n}],i)).get(c)}p(W,"readableRepos");async function g(e,o,r,n){const{defs:i,subjects:c}=n??await _(e,o),a=A(i,c,k,"read",b("o.id")),s=r.length===0?[]:await e.prepareUncached(`SELECT o.*, i.person AS holder, i.scheme AS id_scheme, i.external_id AS id_external, ${a.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
|
|
3
|
+
WHERE o.type = 'repo' AND o.deleted_at IS NULL AND (i.scheme, i.external_id) IN (SELECT * FROM unnest(?::text[], ?::text[]))`).all(...a.params,r.map(t=>t.scheme),r.map(t=>t.externalId)),m=`user:${o.replace(/^user:/,"")}`,w=p(t=>t.holder===m&&t.owner===null,"own"),u=new Map;for(const t of r){const d=s.filter(l=>l.id_scheme===t.scheme&&l.id_external===t.externalId),h=d.filter(l=>l.ok).sort((l,f)=>Number(w(f))-Number(w(l))||l.created_at.localeCompare(f.created_at)||l.seq-f.seq).map(({holder:l,ok:f,id_scheme:q,id_external:J,...I})=>I);u.set(`${t.scheme}\0${t.externalId}`,{readable:h,heldByPerson:d.some(l=>l.holder===m)})}return u}p(g,"readableReposFor");const C=p(async e=>await e.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
|
|
4
|
+
WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all(),"localPathRepos");async function ne(e,o,r,n){const i=new Map;for(const c of r){let a;try{a=await S(e,y(E(c)),async()=>o)}catch(s){if(s instanceof R&&s.code==="git-lookup-failed")continue;throw s}for(const s of a)s.ok&&i.set(`${s.scheme}\0${s.externalId}`,{scheme:s.scheme,externalId:s.externalId})}n.readable=await g(e,o,[...i.values()],n),n.localPaths=await C(e)}p(ne,"prefetchRepoReads");async function ie(e,o){return(await B(e,o)).map(r=>r.repo)}p(ie,"reposForCwd");async function se(e){await j(y(E(e)))}p(se,"warmCheckoutIdentities");async function B(e,o,r,n){const i=y(E(o)),c=[];let a=n;for(const t of await S(e,i,async()=>r??await x())){if(!t.ok)throw new R("git-lookup-failed",`cannot identify the repo at ${t.dir}: ${t.reason}`,O.GENERAL,{dir:t.dir});const d=r??await x();a??=await _(e,d);const{readable:h,heldByPerson:l}=await W(e,d,t.scheme,t.externalId,a);h.length===0&&!l&&h.push(await H(e,t));for(const f of h)c.push({root:t.root,repo:f})}const m=(n?.localPaths??await C(e)).filter(({path:t})=>i===t||i.startsWith(t.endsWith(N)?t:t+N)),w=m.length>0?r??await x():"";for(const{path:t,person:d,...h}of m)d===`user:${w.replace(/^user:/,"")}`&&c.push({root:t,repo:h});c.sort((t,d)=>d.root.length-t.root.length);const u=new Set;return c.filter(({repo:t})=>!u.has(t.id)&&(u.add(t.id),!0))}p(B,"checkoutsForCwd");export{B as checkoutsForCwd,H as ensureRepo,D as handleHint,_ as loadReadAccess,ae as mayRead,ne as prefetchRepoReads,W as readableRepos,ie as reposForCwd,se as warmCheckoutIdentities};
|
|
@@ -42,5 +42,7 @@ export declare function selectProfileForCwdReadOnly(cwd: string): string;
|
|
|
42
42
|
* the root profile. Non-interactive (no TTY):
|
|
43
43
|
* default to the root profile and print the recovery instruction to STDERR —
|
|
44
44
|
* never stdout, which the caller may be piping. */
|
|
45
|
-
export declare function selectProfileForCwd(cwd: string, explicitProfile?: string | null, forcePicker?: boolean
|
|
45
|
+
export declare function selectProfileForCwd(cwd: string, explicitProfile?: string | null, forcePicker?: boolean,
|
|
46
|
+
/** The front door's startup does not hold the start on the last-used write (a timestamp nothing in this start reads back); crtrd's callers wait for it. */
|
|
47
|
+
waitForLastUsed?: boolean): Promise<string>;
|
|
46
48
|
export {};
|
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
var se=Object.defineProperty;var l=(t,e)=>se(t,"name",{value:e,configurable:!0});import{projectPaths as P}from"../../api/dto/profiles.js";import{spawnSync as le}from"node:child_process";import{existsSync as ae,realpathSync as ce}from"node:fs";import{basename as fe,
|
|
1
|
+
var se=Object.defineProperty;var l=(t,e)=>se(t,"name",{value:e,configurable:!0});import{projectPaths as P}from"../../api/dto/profiles.js";import{spawnSync as le}from"node:child_process";import{existsSync as ae,realpathSync as ce}from"node:fs";import{basename as fe,join as ue,resolve as pe,sep as A}from"node:path";import{appendRotatingRecord as de}from"../log.js";import{crtrHome as me}from"../canvas/paths.js";import{createInterface as M}from"node:readline/promises";import{emitKeypressEvents as E}from"node:readline";import{listProfiles as D,loadProfileManifest as he,resolveProfileOperand as $e,updateProfileLastUsed as O,createProfile as ge,addProfileProject as j,ensureRootProfile as k,ROOT_PROFILE_ID as L}from"./manifest.js";import{getDefaultProfileId as we,setDefaultProfileId as Ie,clearDefaultProfile as N}from"./default-binding.js";import{tildify as b}from"../fs-utils.js";import{stdoutColor as T}from"../output.js";import{inTmux as ye}from"../runtime/placement-tmux.js";import{surfaceTmuxStyleArgs as xe}from"../runtime/surface-bg.js";import{formatBinding as g,matchesTerminalInput as Pe,resolveUserKeybindings as be}from"../keybindings/index.js";const ve=["crtr.profile.menu.abort","crtr.profile.menu.up","crtr.profile.menu.down","crtr.profile.menu.select","crtr.profile.menu.accept-default","crtr.profile.menu.slot.1","crtr.profile.menu.slot.2","crtr.profile.menu.slot.3","crtr.profile.menu.slot.4","crtr.profile.menu.slot.5","crtr.profile.menu.slot.6","crtr.profile.menu.slot.7","crtr.profile.menu.slot.8","crtr.profile.menu.slot.9","crtr.profile.menu.create","crtr.profile.menu.search-existing","crtr.profile.menu.use-root","crtr.profile.menu.set-default","crtr.profile.menu.add-directory","crtr.profile.menu.unpin","crtr.profile.menu.manage"],Me=["crtr.profile.search.abort","crtr.profile.search.back","crtr.profile.search.pick","crtr.profile.search.up","crtr.profile.search.down","crtr.profile.search.delete"];function Y(t,e){return{input:e.ctrl===!0||e.meta===!0?e.name??t:t,upArrow:e.name==="up",downArrow:e.name==="down",return:e.name==="return"||e.name==="enter",escape:e.name==="escape",backspace:e.name==="backspace",ctrl:e.ctrl,meta:e.meta,shift:e.shift}}l(Y,"profileRawInput");function B(t,e,r){return e.find(n=>Pe(t,n,r))??null}l(B,"firstProfileMatch");function Te(t,e){return B(t,ve,e)}l(Te,"resolveProfileMenuAction");function _e(t,e){return B(t,Me,e)}l(_e,"resolveProfileSearchAction");function W(t){const e=pe(t);if(!ae(e))return e;try{return ce(e)}catch{return e}}l(W,"resolveCwd");function F(t,e){return!!(t===e||t.startsWith(e+A)||e.startsWith(t+A))}l(F,"projectCovers");function H(t,e){return P(t.manifest.projects).some(r=>F(e,r))}l(H,"profileCoversCwd");function _(t,e){return t===null?!1:e===null?!0:t>e}l(_,"isMoreRecent");function U(t){return t.reduce((e,r)=>_(r.manifest.last_used_at,e.manifest.last_used_at)?r:e)}l(U,"pickMostRecent");function K(t){const e=W(t),r=D().filter(o=>H(o,e)),n=r.filter(o=>P(o.manifest.projects).includes(e)),i=we(e),s=i===null?null:r.find(o=>o.profileId===i)??null;return{covering:r,exact:n,pinnedId:i,pinned:s}}l(K,"profileSelectionState");function Ze(t){const{covering:e,exact:r,pinned:n}=K(t);if(n!==null)return n.profileId;if(r.length===1)return r[0].profileId;const i=r.length>0?r:e;return i.length>0?U(i).profileId:L}l(Ze,"selectProfileForCwdReadOnly");function q(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}l(q,"isInteractive");const $=T.dim,x=T.bold,y=T.cyan;function Re(t){return y(x(t))}l(Re,"key");function G(t){if(t===null)return"never used";const e=Date.parse(t);if(Number.isNaN(e))return"used recently";const r=Math.max(0,Math.floor((Date.now()-e)/1e3));if(r<60)return"used just now";const n=Math.floor(r/60);if(n<60)return`used ${n}m ago`;const i=Math.floor(n/60);if(i<24)return`used ${i}h ago`;const s=Math.floor(i/24);if(s<30)return`used ${s}d ago`;const o=Math.floor(s/30);return o<12?`used ${o}mo ago`:`used ${Math.floor(o/12)}y ago`}l(G,"relativeUsed");function Ce(t,e){const r=e!==void 0?` ${$(e)}
|
|
2
2
|
`:"";process.stdout.write(`
|
|
3
3
|
${x(t)}
|
|
4
4
|
${r}
|
|
5
|
-
`)}l(
|
|
6
|
-
`),n=r.length-1;let
|
|
5
|
+
`)}l(Ce,"writeHeader");function Se(t){const e=P(t.manifest.projects),r=e.length,n=e[0];return n===void 0?G(t.manifest.last_used_at):r>1?`${b(n)} \xB7 ${r} dirs total`:b(n)}l(Se,"purviewSummary");const J=y("\u25B8"),z=l(t=>t>0?`\x1B[${t}A\r`:"","cursorUp"),Q="\x1B[0J",Ae=/\u001b\[[0-9;]*m/g;function V(t){const e=process.stdout.columns??80,r=t.split(`
|
|
6
|
+
`),n=r.length-1;let i=0;for(let s=0;s<n;s++){const o=r[s].replace(Ae,"").length;e>0&&o>e&&(i+=Math.ceil(o/e)-1)}return n+i}l(V,"blockRows");function Ee(t,e,r,n,i,s){let o=`
|
|
7
7
|
${x(e)}
|
|
8
8
|
`;r!==void 0&&(o+=` ${$(r)}
|
|
9
9
|
`),o+=`
|
|
10
|
-
`;let
|
|
11
|
-
`}return
|
|
12
|
-
${$(
|
|
10
|
+
`;let a=0;for(const[d,h]of n.entries()){const c=h.bindingId===void 0?++a:0,m=h.bindingId!==void 0?g(t,h.bindingId):c<=9?g(t,`crtr.profile.menu.slot.${c}`):"",u=d===i?J:" ",p=h.detail!==""?" "+$(h.detail):"",f=h.isDefault?" "+y("\xB7 "+(h.defaultText??"default")):"";o+=` ${u} ${Re(m)} ${h.label}${p}${f}
|
|
11
|
+
`}return s!==void 0&&(o+=`
|
|
12
|
+
${$(s)}
|
|
13
13
|
`),o+=`
|
|
14
|
-
${$(`${
|
|
15
|
-
`,o}l(
|
|
16
|
-
`),process.exit(130)),
|
|
17
|
-
`),!1)}l(Z,"openProfileManager");const R=Symbol("profile-manager-ran");function ee(t){return` ${
|
|
14
|
+
${$(`${g(t,"crtr.profile.menu.up")}/${g(t,"crtr.profile.menu.down")} move ${g(t,"crtr.profile.menu.select")} select ${g(t,"crtr.profile.menu.accept-default")} default ${g(t,"crtr.profile.menu.abort")} quit`)}
|
|
15
|
+
`,o}l(Ee,"renderMenu");function X(t,e,r,n,i={}){const s=[];n.forEach((a,d)=>{a.bindingId===void 0&&s.push(d)});let o=i.initialIndex??0;return new Promise(a=>{let d=0;const h=l(()=>{const u=Ee(t,e,r,n,o,i.hint);process.stdout.write((d>0?z(d)+Q:"")+u),d=V(u)},"draw"),c=l(()=>{process.stdin.off("keypress",m),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),m=l((u,p)=>{const f=Te(t,Y(u,p));if(f==="crtr.profile.menu.abort"&&(c(),process.stdout.write(`
|
|
16
|
+
`),process.exit(130)),f==="crtr.profile.menu.up"){o=(o-1+n.length)%n.length,h();return}if(f==="crtr.profile.menu.down"){o=(o+1)%n.length,h();return}if(f==="crtr.profile.menu.select"){c(),a({index:o});return}if(f==="crtr.profile.menu.accept-default"){c(),a({index:i.initialIndex??0});return}if(f?.startsWith("crtr.profile.menu.slot.")){const I=Number.parseInt(f.slice(-1),10);I>=1&&I<=s.length&&(o=s[I-1],h());return}const w=n.findIndex(I=>I.bindingId!==void 0&&I.bindingId===f);if(w>=0){c(),a({index:w});return}f!==null&&i.actionBindingIds?.includes(f)===!0&&(c(),a({index:o,action:f}))},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",m),h()})}l(X,"runMenu");function Z(t){return ye()?(le("tmux",["display-popup","-E","-T"," profiles ","-w","90%","-h","85%","-d",t,...xe(),"crtr sys settings --page profiles"],{stdio:"inherit"}),!0):(process.stdout.write(` ${$("the profile manager needs tmux \u2014 run `crtr sys settings` instead")}
|
|
17
|
+
`),!1)}l(Z,"openProfileManager");const R=Symbol("profile-manager-ran");function ee(t){return` ${y("\u203A")} ${$(t)} `}l(ee,"caret");function De(t){return`crtr: no profile covers ${t}, and this session is non-interactive \u2014 using the root profile.
|
|
18
18
|
Run \`crtr profile new --name <name> --project ${t}\` to create a dedicated profile, or pass --profile <id-or-name> next time.
|
|
19
|
-
`}l(
|
|
20
|
-
`))}l(te,"offerAddDirToProfile");async function
|
|
21
|
-
`),null;let r="",n=0;const
|
|
19
|
+
`}l(De,"rootProfileMessage");async function Oe(t,e){const r=M({input:process.stdin,output:process.stdout});try{Ce(`Profile "${t.manifest.name}" doesn't cover this directory`),await te(r,t,e)}finally{r.close()}}l(Oe,"promptAddDirToProfile");async function te(t,e,r){const n=(await t.question(ee(`add this directory to "${e.manifest.name}"? [Y/n]`))).trim().toLowerCase();n==="n"||n==="no"||(await j(e.profileId,r),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${e.manifest.name}"`)}
|
|
20
|
+
`))}l(te,"offerAddDirToProfile");async function je(t){const e=[...D()].filter(s=>s.profileId!==L).sort((s,o)=>_(s.manifest.last_used_at,o.manifest.last_used_at)?-1:1);if(e.length===0)return process.stdout.write(` ${$("no existing profiles to select")}
|
|
21
|
+
`),null;let r="",n=0;const i=l(()=>r===""?e:e.filter(s=>s.manifest.name.toLowerCase().includes(r)||P(s.manifest.projects).some(o=>b(o).toLowerCase().includes(r))),"matchesOf");return new Promise(s=>{let o=0;const a=l(()=>{const c=i();n>=c.length&&(n=Math.max(0,c.length-1));let m=`
|
|
22
22
|
${x("Select an existing profile")}
|
|
23
|
-
`;if(
|
|
23
|
+
`;if(m+=` ${$("across every profile, not just this directory")}
|
|
24
24
|
|
|
25
|
-
`,c.length===0)
|
|
26
|
-
`;else{const u=Math.max(...c.map(
|
|
27
|
-
`})}
|
|
28
|
-
${
|
|
29
|
-
`,
|
|
30
|
-
`,process.stdout.write((o>0?z(o)+Q:"")+
|
|
31
|
-
`),process.exit(130)),u==="crtr.profile.search.back"){
|
|
32
|
-
`),
|
|
33
|
-
`),
|
|
34
|
-
`)):u.action==="crtr.profile.menu.add-directory"&&(await
|
|
35
|
-
`)),
|
|
25
|
+
`,c.length===0)m+=` ${$(`no match for "${r}"`)}
|
|
26
|
+
`;else{const u=Math.max(...c.map(p=>p.manifest.name.length));c.forEach((p,f)=>{m+=` ${f===n?J:" "} ${x(p.manifest.name.padEnd(u))} ${$(Se(p))}
|
|
27
|
+
`})}m+=`
|
|
28
|
+
${y("\u203A")} ${r}${$("\u2588")}
|
|
29
|
+
`,m+=` ${$(`type to filter ${g(t,"crtr.profile.search.up")}/${g(t,"crtr.profile.search.down")} move ${g(t,"crtr.profile.search.pick")} pick ${g(t,"crtr.profile.search.back")} back`)}
|
|
30
|
+
`,process.stdout.write((o>0?z(o)+Q:"")+m),o=V(m)},"draw"),d=l(()=>{process.stdin.off("keypress",h),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),h=l((c,m)=>{const u=_e(t,Y(c,m));if(u==="crtr.profile.search.abort"&&(d(),process.stdout.write(`
|
|
31
|
+
`),process.exit(130)),u==="crtr.profile.search.back"){d(),s(null);return}const p=i();if(u==="crtr.profile.search.pick"){p.length>0&&(d(),s(p[n].profileId));return}if(u==="crtr.profile.search.up"){p.length>0&&(n=(n-1+p.length)%p.length,a());return}if(u==="crtr.profile.search.down"){p.length>0&&(n=(n+1)%p.length,a());return}if(u==="crtr.profile.search.delete"){r=r.slice(0,-1),n=0,a();return}c!==void 0&&c.length===1&&c>=" "&&m.ctrl!==!0&&(r+=c.toLowerCase(),n=0,a())},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",h),a()})}l(je,"promptSelectExistingProfile");async function re(t,e){const r=fe(e)||"profile",n=(await t.question(ee(`name the new profile [${r}]`))).trim(),i=n!==""?n:r,s=(await ge(i,[{path:e}])).profileId;return process.stdout.write(` ${y("\u2713")} ${$(`created profile "${i}"`)}
|
|
32
|
+
`),s}l(re,"createProfileHere");async function ke(t,e){const r=[{label:"create a profile here",detail:"",bindingId:"crtr.profile.menu.create"},{label:"select an existing profile",detail:"",bindingId:"crtr.profile.menu.search-existing"},{label:$("use the root profile"),detail:"",bindingId:"crtr.profile.menu.use-root",isDefault:!0}];for(;;){const n=await X(e,"No profile covers this directory",void 0,r,{initialIndex:2,actionBindingIds:["crtr.profile.menu.manage"],hint:`${g(e,"crtr.profile.menu.manage")}=manage profiles`});if(n.action==="crtr.profile.menu.manage"){if(Z(t))return R;continue}if(n.index===0){const i=M({input:process.stdin,output:process.stdout});try{return await re(i,t)}finally{i.close()}}if(n.index===1){const i=await je(e);if(i===null)continue;const s=he(i),o=M({input:process.stdin,output:process.stdout});try{await te(o,s,t)}finally{o.close()}return s.profileId}return(await k()).profileId}}l(ke,"promptCreateOrRoot");async function C(t,e,r,n,i){const s=[...t].sort((f,w)=>_(f.manifest.last_used_at,w.manifest.last_used_at)?-1:1),o=n!==null?s.find(f=>f.profileId===n)??null:null,a=o!==null?[o,...s.filter(f=>f!==o)]:s,d=Math.max(...a.map(f=>f.manifest.name.length)),h=a.map((f,w)=>{const I=P(f.manifest.projects),v=I.length,ne=r?`${G(f.manifest.last_used_at)}${v>1?` \xB7 ${v} dirs total`:""}`:(()=>{const S=I.find(ie=>F(e,ie))??I[0];return v>1?`matches ${b(S)} \xB7 ${v} dirs total`:`matches ${b(S)}`})(),oe=o!==null&&a[0]===o?"default (pinned)":"default";return{label:x(f.manifest.name.padEnd(d)),detail:ne,isDefault:w===0,defaultText:oe}});h.push({label:$("create a new profile here"),detail:"",bindingId:"crtr.profile.menu.create"});const c=["crtr.profile.menu.set-default","crtr.profile.menu.manage"];r||c.push("crtr.profile.menu.add-directory"),o!==null&&c.push("crtr.profile.menu.unpin");const m=[`${g(i,"crtr.profile.menu.set-default")}=set default`];r||m.push(`${g(i,"crtr.profile.menu.add-directory")}=add dir here`),o!==null&&m.push(`${g(i,"crtr.profile.menu.unpin")}=unpin`),m.push(`${g(i,"crtr.profile.menu.manage")}=manage profiles`);const u=await X(i,r?"Choose a profile":"Select a profile",r?"Several profiles claim this directory as their project":"This directory falls under existing profile(s)",h,{actionBindingIds:c,hint:m.join(" ")});if(u.action==="crtr.profile.menu.manage")return Z(e)?R:await C(t,e,r,n,i);if(u.index>=a.length){const f=M({input:process.stdin,output:process.stdout});try{return await re(f,e)}finally{f.close()}}const p=a[u.index];return u.action==="crtr.profile.menu.unpin"?(await N(e),process.stdout.write(` ${y("\u2713")} ${$("cleared the default for this directory")}
|
|
33
|
+
`),p.profileId):(u.action==="crtr.profile.menu.set-default"?(await Ie(e,p.profileId),process.stdout.write(` ${y("\u2713")} ${$(`"${p.manifest.name}" is now the default here`)}
|
|
34
|
+
`)):u.action==="crtr.profile.menu.add-directory"&&(await j(p.profileId,e),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${p.manifest.name}"`)}
|
|
35
|
+
`)),p.profileId)}l(C,"promptPickProfileOrCreate");async function et(t,e,r=!1,n=!0){const i=l(async a=>{n?await O(a):O(a).catch(d=>de(ue(me(),"attach-invariants.log"),`${new Date().toISOString()} profile.last_used ${a} ${String(d).replaceAll(/[\r\n]/g," ")}`))},"touch"),s=W(t),o=be();if(e!=null&&e!==""){const a=$e(e);return!H(a,s)&&q()&&await Oe(a,s),await i(a.profileId),a.profileId}for(;;){const{covering:a,exact:d,pinnedId:h,pinned:c}=K(s);if(h!==null&&c===null&&await N(s),c!==null&&!r)return await i(c.profileId),c.profileId;if(!r&&c===null&&d.length===1)return await i(d[0].profileId),d[0].profileId;if(!q()){const p=d.length>0?d:a;if(p.length>0){const w=U(p);return await i(w.profileId),w.profileId}const f=await k();return process.stderr.write(De(s)),f.profileId}const m=c!==null?c.profileId:null,u=d.length>1?await C(d,s,!0,m,o):a.length>0?await C(a,s,!1,m,o):await ke(s,o);if(u!==R)return await i(u),u}}l(et,"selectProfileForCwd");export{H as profileCoversCwd,Te as resolveProfileMenuAction,_e as resolveProfileSearchAction,et as selectProfileForCwd,Ze as selectProfileForCwdReadOnly};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Cron } from '../canvas/index.js';
|
|
1
|
+
import { type Cron, type NodeMeta } from '../canvas/index.js';
|
|
2
2
|
import type { DeliveredDoc, RenderContext } from '../substrate/delivery/render-event.js';
|
|
3
3
|
import { buildProjectContextBlock, contextDirNote, orchestratorContextNote } from './bearings-render.js';
|
|
4
4
|
/** The bearings custom type is shared with every attached renderer. */
|
|
@@ -13,11 +13,11 @@ export { buildProjectContextBlock, contextDirNote, orchestratorContextNote };
|
|
|
13
13
|
* `assembleNodeSubject`'s profile resolution). This absolute-path disclosure
|
|
14
14
|
* is intentional (spec-approved): the agent must know its full purview, not a
|
|
15
15
|
* redacted count. */
|
|
16
|
-
export declare function profileNote(nodeId: string): Promise<string>;
|
|
16
|
+
export declare function profileNote(nodeId: string, known?: NodeMeta | null): Promise<string>;
|
|
17
17
|
/** The graph mini-map: the ancestry trunk (root first), then this node marked
|
|
18
18
|
* `● you`, then its immediate children. Returns '' for a lone root with no
|
|
19
19
|
* children (nothing to map). Exported for testing. */
|
|
20
|
-
export declare function buildGraphMap(nodeId: string): Promise<string>;
|
|
20
|
+
export declare function buildGraphMap(nodeId: string, known?: NodeMeta | null): Promise<string>;
|
|
21
21
|
/** Why a node was born or woken, as carried from the fired cron to the
|
|
22
22
|
* injection seam. `ownerName` is the armer's resolved display name when it
|
|
23
23
|
* still exists (a reaped cron's armer renders as a bare id, never crashes). */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var b=Object.defineProperty;var a=(e,
|
|
2
|
-
${
|
|
1
|
+
var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,fullName as d,isSafeNodeId as k,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as w,orchestratorContextNote as p,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as V}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":$(n.cwd,n.profile_id)}a(A,"profileNote");async function E(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(E,"ancestorTrunk");const F=5;async function j(e){return(await Y(await g(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(j,"childNodes");async function B(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await E(e,n),o=await j(e);return C(e,n.kind,n.mode,t,o)}a(B,"buildGraphMap");async function R(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&k(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return S(e,r?.kind??"general",r?.mode??"base",n,o)}a(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(T,"armerPhrase");async function K(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(K,"cronWakeOrigin");function q(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
|
|
2
|
+
${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
|
|
3
3
|
</crtr-wake>`;const t=T(e);return`<crtr-wake>
|
|
4
|
-
${
|
|
5
|
-
</crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,n
|
|
6
|
-
`),n,
|
|
7
|
-
`)}a(W,"bearingsShell");async function z(e,
|
|
4
|
+
${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
|
|
5
|
+
</crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,r,n){const t=await s(e),o=["<crtr-bearings>",await R(e,t)],i=await B(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=D(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await _(e)??"",m=t?.cwd!==void 0?f(t.cwd):"";return[o.join(`
|
|
6
|
+
`),r,n,h,m].filter(y=>y!=="").join(`
|
|
7
|
+
`)}a(W,"bearingsShell");async function z(e,r){const n=await v(r),t=await x(r);return{content:await W(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(z,"buildContextBearings");export{V as CONTEXT_INTRO_CUSTOM_TYPE,z as buildContextBearings,B as buildGraphMap,f as buildProjectContextBlock,q as buildWakeBearings,w as contextDirNote,K as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
|
|
@@ -27,8 +27,8 @@ export interface BootRootOpts {
|
|
|
27
27
|
export declare function rootCreateRequest(opts: BootRootOpts, profileId: string): Parameters<ReturnType<typeof cliClient>['createNode']>[0];
|
|
28
28
|
/** Boot the front-door root: create the resident root through crtrd (broker
|
|
29
29
|
* launched + view socket ready server-side), register THIS terminal's pane as
|
|
30
|
-
* its foreground viewer, then
|
|
31
|
-
* becomes a writable viewer. Does not return — it process.exit()s
|
|
32
|
-
* when the
|
|
30
|
+
* its foreground viewer, then run the attach viewer in this process so this
|
|
31
|
+
* terminal becomes a writable viewer. Does not return — it process.exit()s
|
|
32
|
+
* when the viewer exits (detach leaves the resident broker running, to
|
|
33
33
|
* be reconnected later). */
|
|
34
34
|
export declare function bootRoot(opts: BootRootOpts): Promise<never>;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
3
|
-
${
|
|
1
|
+
var x=Object.defineProperty;var p=(e,o)=>x(e,"name",{value:o,configurable:!0});import{inTmux as b,currentTmux as w}from"./placement-tmux.js";import{selectProfileForCwd as g}from"../profiles/select.js";import{cliClient as c}from"../../commands/api-client.js";import{mark as s}from"../timing.js";import{handle as T}from"../io.js";import{loadedPersonSettings as k}from"../../commands/person-settings.js";import{showStartingScreen as C}from"./starting-screen.js";import{printComeBackNote as l}from"./come-back-note.js";function h(e,o){const i=e.kind;return{...i!==void 0?{kind:i}:{},mode:"base",prompt:e.prompt,profile:o,cwd:e.cwd,...e.name!==void 0?{name:e.name}:i!==void 0?{name:i}:{},root:!0,start:!0,prefer_warm:!0}}p(h,"rootCreateRequest");async function R(e){if(!b()){const t=process.stderr.isTTY?r=>`\x1B[1;33m${r}\x1B[0m`:r=>r;process.stderr.write(`
|
|
2
|
+
${t("crtr must be started from inside a tmux session.")}
|
|
3
|
+
${t("Start tmux first, e.g. tmux new -s work \u2014 then run crtr there.")}
|
|
4
4
|
|
|
5
|
-
`),process.exit(1)}
|
|
5
|
+
`),process.exit(1)}s("boot_root.start");const o=e.selectedProfileId??await g(e.cwd,e.profile,e.pickProfile??!1,!1);if(s("boot_root.profile_resolved"),!process.stdout.isTTY){const t=await c().createNode(h(e,o)),r=w();r!==null&&await c().registerFocus({node_id:t.node_id,pane:r.pane,session:r.session,window:r.window}).catch(()=>{}),process.stdout.write(`crtr surface attach is an interactive terminal viewer \u2014 run it in a tmux pane (a TTY), not a pipe. Node: ${t.node_id}
|
|
6
|
+
`),await l(t.node_id,0),process.exit(0)}const{buildBannerInfo:i}=await import("../../clients/attach/session/banner.js"),{hint:$,..._}=i({cwd:e.cwd,profile_id:o}),a=C(_);s("boot_root.starting_painted");const f=import("../../clients/attach/viewer.js");f.catch(()=>{});let m;try{m=await c().createNode(h(e,o))}catch(t){throw a.stop(),t}const n=m.node_id;a.setNode(n),s("boot_root.node_created",{node:n});const d=w();d!==null&&c().registerFocus({node_id:n,pane:d.pane,session:d.session,window:d.window}).catch(()=>{});let u=0;try{const{runAttach:t}=await f;s("boot_root.viewer_attach"),await t(n,!1,void 0,!0,{node:m,settings:k(),initialWhip:e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")},()=>a.stop())}catch(t){a.stop(),process.stderr.write(`crtr: the agent ${n} is still running; reopen it with crtr -r ${n}
|
|
7
|
+
`),T(t),process.exit(typeof process.exitCode=="number"?process.exitCode:1)}await l(n,u),process.exit(u)}p(R,"bootRoot");export{R as bootRoot,h as rootCreateRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{getNode as s}from"../canvas/index.js";import{openDb as c,withCanvasWrite as l}from"../canvas/db.js";import{readerForNode as u,warmNodeRepos as f}from"../graph/reader.js";import{checkoutsForCwd as p}from"../graph/repo-sync/repos.js";import{deliver as v}from"../substrate/delivery/deliver.js";import{oneShotControllerRequest as w}from"./broker-request.js";import{isBrokerLive as d}from"./model-swap.js";import{CONTEXT_INTRO_CUSTOM_TYPE as y}from"./bearings.js";import{formatCard as T}from"../../shared/generated-context.js";async function C(e,t){const r=await s(e);if(r===null)throw new Error(`deliverCustomMessageLive: unknown node ${e}`);d(r)&&await w({nodeId:e,what:`the ${t.customType} delivery`,ackFor:"deliver_custom_message",frame:o(()=>({type:"deliver_custom_message",customType:t.customType,content:t.content,...t.deliverAs!==void 0?{deliverAs:t.deliverAs}:{},...t.details!==void 0?{details:t.details}:{}}),"frame"),result:o(()=>{},"result")})}o(C,"deliverCustomMessageLive");async function R(e){await f(await c(),e);const{content:t}=await l(async r=>await v(r,await u(r,e,async(i,a,n)=>await p(r,i,a,n)),{activity:"boot"}));await C(e,{customType:y,content:T("bearings",{},t),details:{nodeId:e}})}o(R,"deliverBearingsLive");export{R as deliverBearingsLive,C as deliverCustomMessageLive};
|
|
@@ -2,7 +2,7 @@ var E=Object.defineProperty;var p=(i,s)=>E(i,"name",{value:s,configurable:!0});i
|
|
|
2
2
|
`),process.exit(1)),"none"in l?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
|
|
3
3
|
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(a=l.node.profile_id,o=l.node.node_id,I(l.node.cwd)&&(g=l.node.cwd))}if(o===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");m&&e.profile===void 0&&process.stdout.write(`
|
|
4
4
|
Choose a profile
|
|
5
|
-
`),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile):d(e.cwd))}const{exitForMissingProviderCredential:f,hasConfiguredProviderCredential:n}=await import("./provider-credential-gate.js"),{cliClient:w}=await import("../../commands/api-client.js"),P=a===null?[]:(await w().listProfileEnv(a)).names,k=p(async()=>{const r=await w().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await n(P)&&!await k()){u||f();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||f()}const{inTmux:R}=await import("./placement-tmux.js");if(u&&!R()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,o!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
|
|
5
|
+
`),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{exitForMissingProviderCredential:f,hasConfiguredProviderCredential:n}=await import("./provider-credential-gate.js"),{cliClient:w}=await import("../../commands/api-client.js"),P=a===null?[]:(await w().listProfileEnv(a)).names,k=p(async()=>{const r=await w().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await n(P)&&!await k()){u||f();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||f()}const{inTmux:R}=await import("./placement-tmux.js");if(u&&!R()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,o!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
|
|
6
6
|
${r}
|
|
7
7
|
|
|
8
8
|
`);const d=N();d!==null&&process.stderr.write(`
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface StartingInfo {
|
|
2
|
+
version?: string;
|
|
3
|
+
profile?: string;
|
|
4
|
+
cwd?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface StartingScreen {
|
|
7
|
+
/** Erase the screen and give the terminal back (cursor shown, raw mode off). */
|
|
8
|
+
stop(): void;
|
|
9
|
+
/** Record the created node so an interrupt can say how to reopen it. */
|
|
10
|
+
setNode(nodeId: string): void;
|
|
11
|
+
}
|
|
12
|
+
export declare function showStartingScreen(info: StartingInfo): StartingScreen;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
var R=Object.defineProperty;var e=(s,t)=>R(s,"name",{value:t,configurable:!0});import{homedir as g}from"node:os";import{croutonBannerLines as A}from"./banner.js";const T="\x1B[2m",x="\x1B[0m",D=100,G="\x1B7",E="\x1B8",S="\x1B[J",L="\x1B[2K";function v(s){const t=process.stdout,h=Date.now();let p=!1,r;const c=g(),u=s.cwd===void 0?void 0:s.cwd===c?"~":s.cwd.startsWith(`${c}/`)?`~${s.cwd.slice(c.length)}`:s.cwd,i=A({...s,...u===void 0?{}:{cwd:u}}).join(`\r
|
|
2
|
+
`),d=e(()=>`${T}starting ${((Date.now()-h)/1e3).toFixed(1)}s${x}`,"seconds"),b=e(()=>{t.write(`\r${L}${d()}`)},"tick"),l=e(()=>{t.write(`${E}${S}${i}\r
|
|
3
|
+
\r
|
|
4
|
+
${d()}`)},"drawAll"),w=e(()=>r===void 0?"":`crtr: the agent ${r} is still running; reopen it with crtr -r ${r}
|
|
5
|
+
`,"reopenNote"),$=process.stdin.isTTY===!0,f=e(n=>{n.includes(3)&&(a(),process.stderr.write(w()),process.exit(130))},"onData"),o=e(n=>{a(),process.stderr.write(w()),process.kill(process.pid,n)},"onSignal");$&&(process.stdin.setRawMode(!0),process.stdin.on("data",f),process.stdin.resume()),process.once("SIGTERM",o),process.once("SIGHUP",o),t.on("resize",l);const m=i.split(`\r
|
|
6
|
+
`).reduce((n,M)=>n+Math.max(1,Math.ceil(M.replaceAll(/\u001b\[[0-9;]*m/g,"").length/Math.max(1,t.columns??80))),0)+2;t.write(`\x1B[?25l${`
|
|
7
|
+
`.repeat(m)}\x1B[${m}A${G}${i}\r
|
|
8
|
+
\r
|
|
9
|
+
${d()}`);const I=setInterval(b,D);function a(){p||(p=!0,clearInterval(I),t.off("resize",l),process.off("SIGTERM",o),process.off("SIGHUP",o),t.write(`${E}${S}\x1B[?25h`),$&&(process.stdin.off("data",f),process.stdin.pause(),process.stdin.setRawMode(!1)))}return e(a,"stop"),{stop:a,setNode:e(n=>{r=n},"setNode")}}e(v,"showStartingScreen");export{v as showStartingScreen};
|
|
@@ -27,7 +27,7 @@ export declare function recordContentDelivery(db: CanvasDb, reader: Reader, deli
|
|
|
27
27
|
* inside its boot, and a document read goes through the read route. */
|
|
28
28
|
export declare const DRY_RUN_ONLY: readonly DeliveryActivity[];
|
|
29
29
|
/** One delivery for a live node. Call inside `withCanvasWrite`. */
|
|
30
|
-
export declare function deliver(db: CanvasDb, reader: Reader, req: DeliveryRequestInput): Promise<DeliveryResult>;
|
|
30
|
+
export declare function deliver(db: CanvasDb, reader: Reader, req: DeliveryRequestInput, subject?: NodeConfigSubject): Promise<DeliveryResult>;
|
|
31
31
|
/** A node that does not exist, described by what delivery reads of one:
|
|
32
32
|
* the directory it would work in, its profile and app, and the fields rule
|
|
33
33
|
* `if` conditions see. Every field but `cwd` has a default. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var $=Object.defineProperty;var l=(t,e)=>$(t,"name",{value:e,configurable:!0});import{dirname as P}from"node:path";import{isCloudRole as T}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as H}from"../../runtime/runner/machine/environment.js";import{clearLedger as W,demoteTranscript as x,freezePreferences as
|
|
2
|
-
`),delivered:[...e.delivered,...n.delivered]}}l(je,"hypotheticalBearings");async function
|
|
1
|
+
var $=Object.defineProperty;var l=(t,e)=>$(t,"name",{value:e,configurable:!0});import{dirname as P}from"node:path";import{isCloudRole as T}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as H}from"../../runtime/runner/machine/environment.js";import{clearLedger as W,demoteTranscript as x,freezePreferences as k,loadLedger as Y,saveLedger as B}from"../../graph/exposures.js";import{recordWatches as U}from"../../graph/watches.js";import{publishMany as J}from"../../graph/events.js";import{checkoutsForCwd as h}from"../../graph/repo-sync/repos.js";import{liveLookups as K,profileObject as V,viewRepos as G}from"../../graph/reader.js";import{ownerForGrantee as X}from"../../graph/objects.js";import{resolveName as z}from"../../graph/names.js";import{SCOPE_VOCABULARY as Q}from"../../scopes.js";import{getNode as Z}from"../../canvas/index.js";import{recordMemoryReadsIn as q}from"../../canvas/memory-reads.js";import{lookupProfile as ee}from"../../profiles/manifest.js";import{getDefaultProfileId as te}from"../../profiles/default-binding.js";import{effectiveScopes as ne,profileNameFor as oe,scopeForCwd as ae}from"../subject-fields.js";import{spineDepth as re}from"../subject.js";import{appForNode as ie}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as N}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce}from"../../runtime/bearings.js";import{deliveryDocOf as O,listingCorpora as de,loadCorpus as w,nodeSubject as R,primeBodies as le,viewOwners as pe}from"./corpus.js";import{listingPrefixes as ue}from"./listings.js";import{planDelivery as me}from"./plan.js";import{renderEvent as _,renderExplicitRead as S}from"./render-event.js";import{renderConfigDelta as fe,renderKnowledge as we,renderPreferences as E,renderWorkspaceOpen as D}from"./render-boot.js";import{mapAsync as C}from"../../async-array.js";function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const I="hypothetical";function v(t){return t.node.id===I}l(v,"isHypothetical");async function g(t,e){if(!v(e))return await ie(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(g,"granteeOf");async function ye(t,e,n,o=async(a,c)=>await h(t,a,c)){const a=f(e).node,c=new Set,r=new Date().toISOString(),s=[],i=[];for(const{doc:d,level:p}of n)p!=="content"||c.has(d.object.id)||(c.add(d.object.id),i.push({watcher:a,object:d.object,start:"deliver",opts:{readHeadsKey:d.headsKey}}),s.push({name:d.name,scope:d.ownerHandle,at:r,type:"loaded"}));await U(t,i),await J(t,i.map(d=>({event:"read",object:d.object,actor:a,attrs:{}})),o),v(f(e))||await q(t,a.id,s)}l(ye,"recordContentDelivery");async function A(t,e,n){if(await b(t,e,n))return e;const o=(await h(t,P(n))).filter(a=>!e.repos.some(c=>c.id===a.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(a=>a.repo)],checkouts:[...e.checkouts,...o]}}l(A,"fileReadReader");async function b(t,e,n){const o=await g(t,e);return o==="app:terminal"&&T()&&e.profile!=null&&await H(e.profile.id)!==null&&!N(n,o,e.scopes??[],null)}l(b,"isMacEnforcedRead");async function F(t,e,n){if(!await b(t,e,n))return{absoluteFile:n};const o=new Map;for(const{root:a,repo:c}of e.checkouts)n.startsWith(a.endsWith("/")?a:`${a}/`)&&!o.has(c.id)&&o.set(c.id,a);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(F,"fileReadPayload");async function he(t,e,n){const o=await g(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await b(t,e,n)||N(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(he,"assertReadableFile");async function ve(t){const e=f(t.reader),n=e.node,o=await g(t.db,e),a=await w(t.db,t.reader,["slash-command"]);await le(t.db,a);const c=await C(a,async r=>{const s=await r.body();return{name:r.displayName,command_name:r.displayName,description:r.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:a,commands:c}}l(ve,"slashCommands");function ge(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(ge,"scopeOf");async function be(t,e){const n=[],o=new Set,a=await pe(t,e),c=await de(t,e,a);for(const r of a){const s=c.get(r.id);for(const i of s){n.push({name:i.displayName,kind:i.kind,scope:ge(i),shortForm:i.preview,gatewayVisible:!i.shipped}),o.add(i.displayName);const d=i.displayName===i.name?"":`${i.ownerHandle}/`;for(const p of ue(s,i.name))o.add(`${d}${p}`)}}return{refs:n,names:[...o]}}l(be,"composerNames");async function L(t,e){const n=f(t.reader),{db:o,ledger:a}=t,c=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[i,d]of a.objects)if(d.transcript===void 0)a.objects.delete(i);else{const{system:p,...u}=d;a.objects.set(i,u)}for(const[i,d]of a.listed)d.transcript===void 0?a.listed.delete(i):a.listed.set(i,{transcript:d.transcript});return a.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const r=v(n)?await je(t):await ce(n.node.id,t),s=await E({...t,channel:"system"});return k(a,s.content),{result:{content:r.content},delivered:[...r.delivered,...s.delivered]}}case"system-prompt":{if(a.preferenceSnapshot!==null)return{result:{content:a.preferenceSnapshot},delivered:[]};const r=await E({...t,channel:"system"});return{result:{content:k(a,r.content)},delivered:r.delivered}}case"compact":{for(const r of await w(o,n,["pre-command"]))x(a,r.object.id);return{result:{content:""},delivered:[]}}case"persona":{const r=await fe(t);return{result:{content:r.content},delivered:r.delivered}}case"file-read":{const r=c();await he(o,n,r);const s=await A(o,n,r),i={...t,reader:s},d=await _(i,"file-read",await F(o,n,r),await w(o,s,["file-read"]));return{result:{content:d.content},delivered:d.delivered}}case"command":case"pre-command":{const r=await _(t,e.activity,{command:c()});return{result:{content:r.content},delivered:r.delivered}}case"slash-command":{const{docs:r,commands:s}=await ve(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const i=r.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(i<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const d=r[i],p=await S(t,d,!0);return{result:{content:"",execution_body:s[i].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:d,level:"content"},...p.delivered]}}case"workspace-open":{const r=await D(t);return{result:{content:r.content},delivered:r.delivered}}case"document-read":{const r=await M(o,n,c()),s=await S(t,await O(o,n,r),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await be(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(L,"render");async function je(t){const e=await we(t),n=await D(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
|
|
2
|
+
`),delivered:[...e.delivered,...n.delivered]}}l(je,"hypotheticalBearings");async function M(t,e,n){const o=await z(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(M,"readDocument");const ke=["workspace-open","document-read"];async function et(t,e,n,o){if(ke.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const a=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await W(t,a.id);const c=await Y(t,a.id),r={db:t,reader:e,subject:o??await R(t,e),ledger:c,channel:"transcript"},{result:s,delivered:i}=await L(r,n);return await ye(t,e,i),await B(t,c),s}l(et,"deliver");const Ne={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function tt(t,e){const n=await Z(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await re(t)}}l(tt,"hypotheticalFrom");function Oe(t,e){if(t===null)return null;if(t===void 0||t==="")return te(e);const n=ee(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(Oe,"resolveProfileId");async function nt(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Oe(e.profile,e.cwd),a=await G(t,e.cwd,o,async(p,u,y)=>await h(t,p,u,y),K(t)),{repos:c}=a,r=e.mode??"base",i={class:"node",node:{id:I,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...Q],cwd:e.cwd,...a,profile:o===null?null:await V(t,o,n)},d={kind:e.kind??"general",mode:r,lifecycle:e.lifecycle??(r==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:ae(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...c,...a.projectRepos].map(p=>p.name)};return{reader:i,subject:d}}l(nt,"hypotheticalReader");async function ot(t,e,n,o,a){const r={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...a??await R(t,e),...o},i={db:t,reader:e,subject:s,ledger:r,channel:"transcript"},{result:d}=await L(i,n),p=Ne[n.activity];let u=null;if(p!==void 0){const y=n.activity==="file-read"?await F(t,f(e),n.subject):n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await O(t,e,await M(t,e,n.subject))}:{},j=n.activity==="file-read"&&n.subject!==void 0?await A(t,f(e),n.subject):e;u=await me(t,s,j,await w(t,j,[p]),p,y)}return{result:d,plan:u}}l(ot,"inspect");async function at(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
|
|
3
3
|
FROM watches w JOIN objects o ON o.id = w.object AND o.type = 'document' AND o.deleted_at IS NULL
|
|
4
4
|
JOIN revisions r ON r.document = o.id LEFT JOIN objects a ON a.id = r.author
|
|
5
5
|
WHERE w.watcher = ? AND r.created_at > ? AND (r.author IS NULL OR r.author != ?)
|
|
6
|
-
GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await
|
|
6
|
+
GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await C(o,async({to_seq:a,authors:c,...r})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(r.id,n);return{doc:r,from:s.seq,to:a,authors:c===null?[]:c.split(",")}})}l(at,"changedWhileDone");export{ke as DRY_RUN_ONLY,at as changedWhileDone,et as deliver,tt as hypotheticalFrom,nt as hypotheticalReader,ot as inspect,ye as recordContentDelivery};
|