Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/list-worker-sessions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@flow-state-dev/workforce": patch
---

The workforce client gains `listWorkerSessions(worker)`: the caller's conversations with one worker on its current flow, as `WorkerSessionEntry` rows (`{ session, isDefault }`). The default conversation, the one `ensureWorkerSession` returns, comes first; the rest follow by latest activity. A task's session, a conversation's delegate session, a workstream lead's session and the project coordinator's session for a project are left out, and listing never creates a session (FIX-2158).
26 changes: 23 additions & 3 deletions apps/docs/docs/workforce/workers-on-disk.md
Original file line number Diff line number Diff line change
Expand Up @@ -812,14 +812,13 @@ there. When you only want to check, `findWorkerSession` takes the same argument
session or nothing. Both throw `No worker "<id>" on your roster.` for a worker that isn't on
the user's roster.

Both are built on the session client, which you can call directly. Use it to start a second
conversation with the same worker:
A user can hold more than one conversation with the same worker. Start another with the
session client, naming the worker in `workerId`:

```ts
import { createSessionClient } from "@flow-state-dev/client"

const sessions = createSessionClient({ baseUrl })
const mine = await sessions.listSessions({ flowKind: "agent", userId, state: { workerId: "researcher" } })
const fresh = await sessions.createSession({ flowKind: "agent", userId, state: { workerId: "researcher" } })
```

Expand All @@ -832,6 +831,27 @@ as one that doesn't exist. A session created without a worker is refused. `worke
readonly field of the session's state: nothing can change it after the create. It works the way
a project does in [Example: one session per project](../fundamentals/state-and-scopes.md#example-one-session-per-project).

To show the user all their conversations with a worker, call `listWorkerSessions`:

```ts
const conversations = await workforce.listWorkerSessions("researcher")
// [{ session: { id: "…", flowKind: "agent", … }, isDefault: true },
// { session: { id: "…", flowKind: "agent", … }, isDefault: false }]
```

Each entry is a `WorkerSessionEntry`: the `session` summary, and `isDefault`, which marks the
conversation `ensureWorkerSession` returns. That one comes first. The rest follow by latest
activity, most recent first. The list holds only the calling user's sessions on the worker's
current flow. It never creates a session. Before the first `ensureWorkerSession`, no entry is
marked default, and the list holds only conversations the user started with `createSession`, if
any. It throws the same roster error as the other two calls.

Some sessions with a worker are not conversations and are left out: the session a task handed to
the worker runs in (reach it through the task), a coordinator conversation's session with one of
its delegates, a [workstream](./projects.md#workstreams)'s lead session, and your [project coordinator](./projects.md#talking-to-a-project)'s session for a project
(`ensureWorkerSession({ worker, projectId })`). So is a session on a flow the worker ran on before
you moved it. Entries carry no title, and opening one is an ordinary action on `session.id`.

**3. Talk to it.** An ordinary action on that session:

```ts
Expand Down
11 changes: 10 additions & 1 deletion packages/workforce/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1858,7 +1858,12 @@ to a model as [tools](#hire-fork-and-fire-as-tools).
Two calls at once get the same session. Messages from other workers (see
[Worker messages](#worker-messages)) land in it. A session the user started at any other id is
never returned. `findWorkerSession` takes the same argument and returns
the session or `undefined`, creating nothing. Both throw `No worker "<id>" on your roster.` for a
the session or `undefined`, creating nothing. `listWorkerSessions(worker)` returns every
conversation the user has with the worker on its current flow, whatever id it was opened at,
as `{ session, isDefault }` entries: the one `ensureWorkerSession` returns comes first with
`isDefault: true`, the rest follow by latest activity. It creates nothing, and leaves out a
task's session, a coordinator's delegate session, a workstream lead's session and a project
coordinator's session. All three throw `No worker "<id>" on your roster.` for a
worker that isn't on the user's roster. The roster flow keeps one session per user, of the
flow kind `workforce-roster`; if you list every flow's sessions, filter out
`flowKind === "workforce-roster"`. Two first calls at once may create two roster sessions, which
Expand Down Expand Up @@ -2284,7 +2289,11 @@ tool a sent message is a call to), `WORKER_MESSAGE_ENTRY`, `WORKER_MESSAGES_PATT
| `workerConfigOf(ctx)` | The configuration of the worker the turn loaded, synchronously, for a prompt, a tool list or a step condition. Throws when the turn loaded no worker: call `installation.resolveWorker` in the flow's `request.onStarted`. |
| `createWorkerHireBlocks(installation)` | `{ hire, fork, edit, fire }`: writes to the caller's own roster, each checked as a turn would check it before anything is written, each refusing a standard worker's id. |
| `defineWorkerRosterFlow(installation, actions?)` | The roster flow (`workforce-roster`), which declares the two worker collections so a client reads a user's roster through one session of it. Mount the hire blocks on it as actions. |
<<<<<<< HEAD
| `createWorkforceClient({ userId, baseUrl?, apiPath?, fetcher? })` | `roster()`, `findWorkerSession(criteria)`, `ensureWorkerSession(criteria)`, `listWorkerSessions(worker)` (the user's conversations with the worker as `WorkerSessionEntry` rows, `{ session, isDefault }`, the default first, then by latest activity) and `standingRules(worker, input)` (see [Standing rules](#standing-rules)), over the session and resource clients. `criteria` is a `WorkerSessionCriteria`: `worker`, and optional keys such as `projectId`, which finds or starts the user's project coordinator for that project. From `./browser` only. |
=======
| `createWorkforceClient({ userId, baseUrl?, apiPath?, fetcher? })` | `roster()`, `findWorkerSession(criteria)`, `ensureWorkerSession(criteria)`, `standingRules(worker, input)` (see [Standing rules](#standing-rules)) and `setWorkProject(worker, { visibility, id }, { sessionId? })` (see [Projects](#projects)), over the session and resource clients. `criteria` is a `WorkerSessionCriteria`: `worker`, and optional keys such as `projectId`, which finds or starts the user's project coordinator for that project. From `./browser` only. |
>>>>>>> origin/main
| `RULE_TOOLS`, `MAX_RULES`, `MAX_RULE_CHARS`, `STANDING_RULES_ACTION`, `STANDING_RULES_LINE`, `STANDING_RULES_RESOURCE` | The four rule tools' names, the list's limits (20 and 300), the flow action `standingRules` calls, the `agentName` a rule write's line carries, and the resource the list is kept under. All but `STANDING_RULES_RESOURCE` are also exported from `./browser`. |
| `SET_WORK_PROJECT_ACTION` / `setWorkProjectAction` / `WORK_PROJECT_STATE_KEY` | The action `setWorkProject` calls (`"setWorkProject"`), the action itself for a worker flow of your own to declare under that name, and the server-owned session-state field it writes (`"workProjectId"`, `<visibility>/<id>`). The two constants are also exported from `./browser`. |
| `deriveWorkerSessionId({ userId, orgId, flow, criteria })` / `isDerivedWorkerSessionId(id)` | The id `ensureWorkerSession` creates a session at, and the shape a worker flow's create check reserves for the user it derives to. |
Expand Down
1 change: 1 addition & 0 deletions packages/workforce/src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
export {
createWorkforceClient,
type RosterEntry,
type WorkerSessionEntry,
type WorkforceClient,
type WorkforceClientOptions
} from "./workers/client";
Expand Down
61 changes: 56 additions & 5 deletions packages/workforce/src/workers/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/**
* `createWorkforceClient`: find or start a session with a worker, from an app.
* `createWorkforceClient`: find or start a session with a worker, or list a
* user's conversations with one, from an app.
*
* Built on the session and resource clients, with no endpoint of its own. The
* user's roster is read through a session of the roster flow (one per user),
Expand All @@ -26,7 +27,7 @@ import {
} from "./derive-session-id";
import { ownerSegment } from "@flow-state-dev/core/types";
import { workstreamsAccessor, workstreamStorageKey, type WorkstreamAddress } from "../projects/workstream-ref";
import { FILING_SESSION_STATE_KEY, ROSTER_FLOW, SET_WORK_PROJECT_ACTION, STANDARD_WORKERS_RESOURCE, WORKERS_RESOURCE } from "./keys";
import { FILING_SESSION_STATE_KEY, ROSTER_FLOW, SET_WORK_PROJECT_ACTION, STANDARD_WORKERS_RESOURCE, WORKER_ID_STATE_KEY, WORKERS_RESOURCE } from "./keys";
import { STANDING_RULES_ACTION } from "../standing-rules/keys";
import type { StandingRulesActionInput, StandingRulesActionOutput } from "../standing-rules/rules-action";
import type { SetWorkProjectOutput } from "../projects/work-project";
Expand Down Expand Up @@ -58,6 +59,13 @@ export type RosterEntry = {
forkedFrom: string | null;
};

/** One of a user's conversations with a worker, as {@link WorkforceClient.listWorkerSessions} returns it. */
export type WorkerSessionEntry = {
session: SessionSummary;
/** True for the conversation `findWorkerSession({ worker })` returns. */
isDefault: boolean;
};

/** A user's roster, and their sessions with each worker. */
export interface WorkforceClient {
/**
Expand Down Expand Up @@ -92,6 +100,15 @@ export interface WorkforceClient {
* user's roster.
*/
ensureWorkerSession(criteria: WorkerSessionCriteria): Promise<SessionSummary>;
/**
* The user's top-level sessions with `worker` on its current flow, opened
* at any id. The default (`findWorkerSession({ worker })`) comes first and
* is marked; the rest follow by latest activity. A task's session, a
* delegate session, a workstream lead's session and the project
* coordinator's session for one project are left out. Never creates the
* default. Throws when the worker isn't on the user's roster.
*/
listWorkerSessions(worker: string): Promise<WorkerSessionEntry[]>;
/**
* Read or edit the user's standing rules with `worker`, in that user's
* session with the worker. The worker's flow must declare the rules action
Expand Down Expand Up @@ -122,10 +139,29 @@ function stateOf(session: SessionSummary): Record<string, unknown> {
return state !== null && typeof state === "object" ? (state as Record<string, unknown>) : {};
}

function mostRecent<T extends { updatedAt: number; createdAt: number }>(rows: readonly T[]): T | undefined {
return [...rows].sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt)[0];
type Timed = { updatedAt: number; createdAt: number };

/** Latest activity first. */
const byRecent = (a: Timed, b: Timed): number => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt;

function mostRecent<T extends Timed>(rows: readonly T[]): T | undefined {
return [...rows].sort(byRecent)[0];
}

/**
* Whether `row` carries no criteria key but the ones `named` holds. A session
* carrying another is a task's, a conversation's delegate, a workstream's
* lead, or the project coordinator's for one project, which only its
* coordinator's sessions carry.
*/
function carriesOnly(row: SessionSummary, named: ReadonlySet<string>): boolean {
const state = stateOf(row);
return CRITERIA_STATE_KEYS.every((key) => named.has(key) || !Object.hasOwn(state, key));
}

/** The criteria keys a lookup by worker alone names. */
const WORKER_ONLY: ReadonlySet<string> = new Set([WORKER_ID_STATE_KEY]);

/** How often an action run through the client checks whether its request ended, and how long it waits. */
const ACTION_POLL_MS = 100;
const ACTION_TIMEOUT_MS = 30_000;
Expand Down Expand Up @@ -260,7 +296,7 @@ export function createWorkforceClient(options: WorkforceClientOptions): Workforc
// A session naming a conversation is only ever a dispatch run of it; a
// top-level one is a caller's, from before a create naming one was refused.
if (Object.hasOwn(state, FILING_SESSION_STATE_KEY) && row.parentSessionId == null) return false;
return CRITERIA_STATE_KEYS.every((key) => named.has(key) || !Object.hasOwn(state, key));
return carriesOnly(row, named);
});
if (criteria.workstreamId === undefined) return mostRecent(matching);
// A workstream's entry names its lead's session, and is the one source of
Expand Down Expand Up @@ -345,6 +381,21 @@ export function createWorkforceClient(options: WorkforceClientOptions): Workforc
throw error;
}
},
listWorkerSessions: async (worker) => {
const { id, orgId } = await roster();
const flow = flowOf(await readRoster(id), worker);
const criteria = { worker };
const [defaultId, rows] = await Promise.all([
deriveWorkerSessionId({ userId, orgId, flow, criteria }),
// Top-level only, the listing's default: a task's or a delegate's
// session is a dispatch run. No limit, so this one answer is every row.
sessions.listSessions({ flowKind: flow, userId, state: criteriaState(criteria) })
Comment thread
jhoffner marked this conversation as resolved.
Resolved
]);
return rows
.filter((row) => carriesOnly(row, WORKER_ONLY))
Comment thread
jhoffner marked this conversation as resolved.
Resolved
.sort((a, b) => Number(b.id === defaultId) - Number(a.id === defaultId) || byRecent(a, b))
Comment thread
jhoffner marked this conversation as resolved.
Resolved
.map((session) => ({ session, isDefault: session.id === defaultId }));
},
standingRules: async (worker, input) => {
const session = await client.ensureWorkerSession({ worker });
const flow = flowOf(await readRoster((await roster()).id), worker);
Expand Down
Loading
Loading